-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTree
More file actions
101 lines (95 loc) · 2.37 KB
/
BinarySearchTree
File metadata and controls
101 lines (95 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<iostream>
using namespace std;
//Definition of Node for Binary search tree
struct BstNode {
int data;
BstNode* left;
BstNode* right;
};
void Preorder(BstNode *root) {
// base condition for recursion
// if tree/sub-tree is empty, return and exit
if(root == NULL) return;
cout<<root->data<<" "; // Print data
Preorder(root->left); // Visit left subtree
Preorder(root->right); // Visit right subtree
}
//Function to visit nodes in Inorder
void Inorder(BstNode* root) {
if(root == NULL) return;
Inorder(root->left); //Visit left subtree
cout<<root->data<<" "; //Print data
Inorder(root->right); // Visit right subtree
}
void Postorder(BstNode *root) {
if(root == NULL) return;
Postorder(root->left); // Visit left subtree
Postorder(root->right); // Visit right subtree
cout<<root->data<<" "; // Print data
}
// Function to create a new Node in heap
BstNode* GetNewNode(int data) {
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// To insert data in BST, returns address of root node
BstNode* Insert(BstNode* root,int data) {
if(root == NULL) { // empty tree
root = GetNewNode(data);
}
// if data to be inserted is lesser, insert in left subtree.
else if(data <= root->data) {
root->left = Insert(root->left,data);
}
// else, insert in right subtree.
else {
root->right = Insert(root->right,data);
}
return root;
}
int Findmin(BstNode* root)
{
if(root==NULL){
cout<<"Error tree is empty ";
return -1;
}
while(root->left!=NULL)
{root=root->left;}
return root->data;
}
//To search an element in BST, returns true if element is found
bool Search(BstNode* root,int data) {
if(root == NULL) {
return false;
}
else if(root->data == data) {
return true;
}
else if(data <= root->data) {
return Search(root->left,data);
}
else {
return Search(root->right,data);
}
}
int main() {
BstNode* root = NULL; // Creating an empty tree
/*Code to test the logic*/
root = Insert(root,15);
root = Insert(root,10);
root = Insert(root,20);
root = Insert(root,25);
root = Insert(root,8);
root = Insert(root,12);
cout<<Findmin(root);
//Postorder(root);
// Ask user to enter a number.
/*int number;
cout<<"Enter number be searched\n";
cin>>number;
//If number is found, print "FOUND"
if(Search(root,number) == true) cout<<"Found\n";
else cout<<"Not Found\n";*/
}