forked from krishna14kant/Data-Structures-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Build_and_Traverse_BST.cpp
79 lines (78 loc) · 1.68 KB
/
Build_and_Traverse_BST.cpp
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
//BST - Binary Search Tree
#include<bits/stdc++.h>
using namespace std;
struct Tree
{
int data;
Tree *left;
Tree *right;
};
Tree* newNode(int num){
Tree *node = new Tree;
node->data = num;
node->left = NULL;
node->right = NULL;
return node;
}
Tree* createTree(Tree* root, int num){
if(!root){
Tree *temp = newNode(num);
root = temp;
return root;
}
if(root->data > num ){
root->left = createTree(root->left, num);
}
else{
root->right = createTree(root->right, num);
}
return root;
}
void inorder(Tree *curr){
if(!curr)
return;
inorder(curr->left);
cout << curr->data << " ";
inorder(curr->right);
}
void preorder(Tree *curr){
if(!curr)
return;
cout << curr->data << " ";
preorder(curr->left);
preorder(curr->right);
}
void postorder(Tree *curr){
if(!curr)
return;
postorder(curr->left);
postorder(curr->right);
cout << curr->data << " ";
}
int main(){
Tree *root = NULL;
int num;
cout << "Enter your first node in tree=";
cin >> num;
root = createTree(root, num);
char choice = 'y';
while(choice=='y'){
cout << "Do you want to enter more nodes?\n Press 'y' for yes or 'n' to exit\n";
cin >> choice;
if(choice=='y'){
cout << "Enter next node=";
cin >> num;
root = createTree(root, num);
}
}
cout << "Inorder traversel of tree: ";
inorder(root);
cout << "\n";
cout << "Preorder traversel of tree: ";
preorder(root);
cout << "\n";
cout << "Postorder traversel of tree: ";
postorder(root);
cout << "\n";
return 0;
}