-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreOrderToBST.cpp
140 lines (93 loc) · 2.16 KB
/
preOrderToBST.cpp
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
#include<bits/stdc++.h>
using namespace std;
int imax=INT_MIN;
class Node{
public:
int value;
Node* left;
Node* right;
Node(int v){
value=v;
left=NULL;
right=NULL;
}
};
Node* newNode(int v){
Node* node = new Node(v);
return node;
}
void inorder(Node* root){
if(root){
inorder(root->left);
cout<<root->value<<" ";
inorder(root->right);
}
}
void preorder(Node* root){
if(root){
cout<<root->value<<" ";
preorder(root->left);
preorder(root->right);
}
}
Node* insert(Node*& root, int val){
if(root==NULL)
return newNode(val);
else if( val < root->value)
root->left = insert(root->left, val);
else if(val > root->value)
root->right = insert(root->right , val);
return root;
}
void lvlT(Node* root){
queue<Node*>q;
q.push(root);
Node* temp;
while(!q.empty()){
Node* temp = q.front(); q.pop();
cout<<temp->value<<" ";
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
}
Node* preToBSTUtil(vector<int> preorder,int &preIndex,int low,int high,int n){
if(preIndex > n || low > high)
return NULL;
Node* root = new Node(preorder[preIndex]);
preIndex++;
if(low == high)
return root;
int i=0;
for(i=low;i<=high;i++){
if(preorder[i] > root->value)
break;
}
root->left = preToBSTUtil(preorder,preIndex,preIndex,i-1,n);
root->right = preToBSTUtil(preorder,preIndex,i,high,n);
return root;
}
Node* preToBSt(vector<int> preorder){
int preIndex = 0;
int n = preorder.size();
return preToBSTUtil(preorder,preIndex,0,n-1,n);
}
int main(){
/* Node* root=NULL;
root=insert(root,8);
root=insert(root,5);
root=insert(root,1);
root=insert(root,7);
root=insert(root,10);
root=insert(root,12);
inorder(root);
cout<<"\nLevel Order Traversal \n"<<endl;
lvlT2(root);
cout<<endl;*/
// preorder(root);
vector<int> preorder{8,5,1,7,10,12};
Node* ans = preToBSt(preorder);
lvlT(ans);
return 0;
}