-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathBST.cpp
More file actions
80 lines (74 loc) · 1.19 KB
/
BST.cpp
File metadata and controls
80 lines (74 loc) · 1.19 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
// C++ Code to insert node and to print inorder traversal
// using iteration
#include <bits/stdc++.h>
using namespace std;
// BST Node
class Node {
public:
int val;
Node* left;
Node* right;
Node(int val)
: val(val)
, left(NULL)
, right(NULL)
{
}
};
// Utility function to insert node in BST
void insert(Node*& root, int key)
{
Node* node = new Node(key);
if (!root) {
root = node;
return;
}
Node* prev = NULL;
Node* temp = root;
while (temp) {
if (temp->val > key) {
prev = temp;
temp = temp->left;
}
else if (temp->val < key) {
prev = temp;
temp = temp->right;
}
}
if (prev->val > key)
prev->left = node;
else
prev->right = node;
}
// Utiltiy function to print inorder traversal
void inorder(Node* root)
{
Node* temp = root;
stack<Node*> st;
while (temp != NULL || !st.empty()) {
if (temp != NULL) {
st.push(temp);
temp = temp->left;
}
else {
temp = st.top();
st.pop();
cout << temp->val << " ";
temp = temp->right;
}
}
}
// Driver code
int main()
{
Node* root = NULL;
insert(root, 30);
insert(root, 50);
insert(root, 15);
insert(root, 20);
insert(root, 10);
insert(root, 40);
insert(root, 60);
inorder(root);
return 0;
}