-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathbuild_bst.c++
More file actions
59 lines (57 loc) · 1.26 KB
/
build_bst.c++
File metadata and controls
59 lines (57 loc) · 1.26 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
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *left,*right;
//Constructor:
node(int data)
{
this->data=data;
left=right=NULL;
}
};
//Build Binary Search Tree:
node *buildBinarySearchTree(node *root , int data)
{
if(root==NULL)
{
node *temp=new node(data);
return temp;
}
if(data < root->data)
{
root->left=buildBinarySearchTree(root->left , data);
}
else if(data > root->data)
{
root->right=buildBinarySearchTree(root->right , data);
}
return root;
}
//Inorder Traversal:
void inOrderTraversal(node * root)
{
if(root==NULL)
{
return;
}
inOrderTraversal(root->left);
cout<<root->data<<" ";
inOrderTraversal(root->right);
}
//Main Function:
int main(int argc, char const *argv[])
{
node *root = buildBinarySearchTree(root , 8);
root = buildBinarySearchTree(root , 6);
root = buildBinarySearchTree(root , 10);
root = buildBinarySearchTree(root , 5);
root = buildBinarySearchTree(root , 7);
root = buildBinarySearchTree(root , 9);
root = buildBinarySearchTree(root , 11);
inOrderTraversal(root);
cout<<endl;
return 0;
}