forked from sat5297/hacktober-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertInBST.cpp
More file actions
75 lines (61 loc) · 1012 Bytes
/
insertInBST.cpp
File metadata and controls
75 lines (61 loc) · 1012 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node* left, *right;
node(int d) {
this->data = d;
left = NULL;
right = NULL;
}
};
node* construct(node* root, int data) {
if (root == NULL) {
node* root = new node(data);
return root;
}
if (data > root->data) {
root->right = construct(root->right, data);
} else {
root->left = construct(root->left, data);
}
return root;
}
node* constructIteratively(node* root, int data) {
node* q = new node(data);
if (root == NULL) {
return q;
}
node* p = root;
while (true) {
if (data < p->data) {
if (p->left == NULL) {
p->left = q;
break;
}
p = p->left;
} else {
if (p->right == NULL) {
p->right = q;
break;
}
p = p->right;
}
}
return root;
}
node* buildTree() {
int data;
cin >> data;
node* root = NULL;
while (data != -1) {
root = constructIteratively(root, data);
cin >> data;
}
return root;
}
int main() {
node *root = buildTree();
return 0;
}