Skip to content

Commit de36685

Browse files
Insert In BST Implemented
1 parent 528f70a commit de36685

File tree

4 files changed

+130
-2
lines changed

4 files changed

+130
-2
lines changed

input.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
20 36
33
10 22 30 40
44
5 12 -1 -1 28 -1 38 48
5-
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
5+
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
6+
21

insert_in_bst.cpp

+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Node
5+
{
6+
public:
7+
int val;
8+
Node *left;
9+
Node *right;
10+
Node(int val)
11+
{
12+
this->val = val;
13+
this->left = NULL;
14+
this->right = NULL;
15+
}
16+
};
17+
18+
Node *input_binary_tree()
19+
{
20+
int val;
21+
cin >> val;
22+
23+
Node *root;
24+
25+
if (val == -1)
26+
root = NULL;
27+
else
28+
root = new Node(val);
29+
30+
queue<Node *> q;
31+
if (root)
32+
q.push(root);
33+
34+
while (!q.empty())
35+
{
36+
// 1. Q theke ber kore ano
37+
Node *f = q.front();
38+
q.pop();
39+
40+
// 2. Jabotiyo ja kaj ache koro
41+
int l, r;
42+
cin >> l >> r;
43+
44+
Node *left, *right;
45+
46+
if (l == -1)
47+
left = NULL;
48+
else
49+
left = new Node(l);
50+
51+
if (r == -1)
52+
right = NULL;
53+
else
54+
right = new Node(r);
55+
56+
f->left = left;
57+
f->right = right;
58+
59+
// 3. Children gulo k push koro
60+
if (f->left)
61+
q.push(f->left);
62+
if (f->right)
63+
q.push(f->right);
64+
}
65+
return root;
66+
}
67+
68+
void level_order(Node *root)
69+
{
70+
queue<Node *> q;
71+
q.push(root);
72+
while (!q.empty())
73+
{
74+
Node *f = q.front();
75+
q.pop();
76+
77+
cout << f->val << " ";
78+
79+
if (f->left)
80+
q.push(f->left);
81+
if (f->right)
82+
q.push(f->right);
83+
}
84+
}
85+
86+
void insert(Node *&root, int x)
87+
{
88+
if (root == NULL)
89+
{
90+
root = new Node(x);
91+
return;
92+
}
93+
94+
if (x < root->val)
95+
{
96+
if (root->left == NULL)
97+
{
98+
root->left = new Node(x);
99+
}
100+
else
101+
{
102+
insert(root->left, x);
103+
}
104+
}
105+
else
106+
{
107+
if (root->right == NULL)
108+
{
109+
root->right = new Node(x);
110+
}
111+
else
112+
{
113+
insert(root->right, x);
114+
}
115+
}
116+
}
117+
118+
int main()
119+
{
120+
Node *root = input_binary_tree();
121+
int x;
122+
cin >> x;
123+
insert(root, x);
124+
level_order(root);
125+
126+
return 0;
127+
}

insert_in_bst.exe

83.2 KB
Binary file not shown.

output.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
YES
1+
25 20 36 10 22 30 40 5 12 21 28 38 48

0 commit comments

Comments
 (0)