-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructBSTfromPostorder.cpp
More file actions
108 lines (94 loc) · 2.01 KB
/
ConstructBSTfromPostorder.cpp
File metadata and controls
108 lines (94 loc) · 2.01 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
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int x){
data = x;
left = NULL;
right = NULL;
}
};
Node *constructTree (int [], int );
void printInorder (Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
int main ()
{
int t,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int post[n];
for(int i=0;i<n;i++)
scanf("%d",&post[i]);
Node* root = constructTree(post, n);
printInorder(root);
printf("\n");
}
return 0;
}
// } Driver Code Ends
/*Node* constructTreeutil(int post[],int n)
{
Node* root=new Node(post[n-1]);
stack<Node*>s;
s.push(root);
for(int i=n-2;i>=0;--i)
{
Node* x=new Node(post[i]);
Node* temp=NULL;
while(s.size() && post[i]<s.top()->data)
temp=s.top();
s.pop();
if(temp!=NULL)
temp->left=x;
else
s.top()->right=x;
s.push(x);
}
return root;
}
Node* constructTree(int post[],int size)
{
return constructTreeutil(post,size);
}*/
Node* constructTreeUtil(int post[], int n)
{
// Last node is root
Node* root = new Node(post[n - 1]);
stack<Node*> s;
s.push(root);
// Traverse from second last node
for (int i = n - 2; i >= 0; --i)
{
Node* x = new Node(post[i]);
// Keep popping nodes while top()
// of stack is greater.
Node* temp = NULL;
while (s.size() &&
post[i] < s.top()->data)
temp = s.top(), s.pop();
// Make x as left child of temp
if (temp != NULL)
temp->left = x;
// Else make x as right of top
else
s.top()->right = x;
s.push(x);
}
return root;
}
// Function that calls the method
// which contructs the tree
Node* constructTree(int post[], int size)
{
return constructTreeUtil(post, size);
}