-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBST.cpp
More file actions
103 lines (94 loc) · 2.34 KB
/
BST.cpp
File metadata and controls
103 lines (94 loc) · 2.34 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
102
103
#include <iostream>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
class BST
{
private:
node* root;
public:
BST()
{
root = nullptr;
}
void insert1(int x)
{
insert(x, root);
}
void insert(int x, node* r)
{
if(root == nullptr)
{
//Empty tree
node* newNode = new node();
newNode->data = x;
newNode->left = nullptr;
newNode->right = nullptr;
root = newNode;
}
else
{
if(x < r->data)
{
//Insert left
if(r->left == nullptr)
{
node* newNode = new node();
newNode->data = x;
newNode->left = nullptr;
newNode->right = nullptr;
r->left = newNode;
}
else
{
insert(x, r->left);
}
}
else
{
//Insert right
if(r->right == nullptr)
{
node* newNode = new node();
newNode->data = x;
newNode->left = nullptr;
newNode->right = nullptr;
r->right = newNode;
}
else
{
insert(x,r->right);
}
}
}
}
void inorder(node* x)
{
if(x != nullptr)
{
inorder(x->left);
cout<<x->data<<" ";
inorder(x->right);
}
}
void inorder1()
{
//'root' is a private member
inorder(root);
}
};
int main()
{
BST b1;
b1.insert1(12);
b1.insert1(4);
b1.insert1(36);
b1.insert1(48);
//Wrapper function
b1.inorder1();
return 0;
}