-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path35 BST Insertion.cpp
More file actions
146 lines (116 loc) · 2.39 KB
/
35 BST Insertion.cpp
File metadata and controls
146 lines (116 loc) · 2.39 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/*
You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function.
Input Format
You are given a function,
Node * insert (Node * root ,int data) {
}
Constraints
No. of nodes in the tree 500
Output Format
Return the root of the binary search tree after inserting the value into the tree.
Sample Input
4
/ \
2 7
/ \
1 3
The value to be inserted is 6.
Sample Output
4
/ \
2 7
/ \ /
1 3 6
*/
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Solution {
public:
void preOrder(Node *root) {
if( root == NULL )
return;
std::cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
/*
Node is defined as
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
*/
Node *loc=NULL, *locp=NULL;
void find(int x,Node *root)
{
Node *cur=root,*curp=NULL;
while(cur!=NULL)
{
if(cur->data==x)
{
loc=cur;
break;
}
else if(cur->data>x)
{
curp=cur;
cur=cur->left;
}
else
{
curp=cur;
cur=cur->right;
}
}
if(cur==NULL)
{
loc=cur;
locp=curp;
}
}
Node * insert(Node * root, int data) {
find(data,root);
if(loc==NULL)
{
Node *New = new Node(data);
if(locp==NULL)
root=New;
else if(locp->data>data)
locp->left=New;
else
locp->right=New;
}
return root;
}
};
int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
myTree.preOrder(root);
return 0;
}