-
Notifications
You must be signed in to change notification settings - Fork 4
/
postorder_using_one_stack.C
68 lines (63 loc) · 1.42 KB
/
postorder_using_one_stack.C
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
//author @ Ayush Aggarwal
//Postorder traversal of tree using one stack
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *left,*right;
};
struct node* newNode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void postorder(node *root)
{
node *curr = root;
stack <node*> s;
while(!s.empty() or curr!=NULL)
{
if(curr!=NULL)
{
s.push(curr);
curr = curr->left;
}
else
{
node *temp = s.top()->right;
if(temp == NULL)
{
temp = s.top();
cout<<temp->data<<" ";
s.pop();
while(!s.empty() and temp==s.top()->right)
{
temp = s.top();
s.pop();
cout<<temp->data<<" ";
}
}
else
curr = temp;
}
}
}
int main()
{
struct node *root = newNode(10);
root->left = newNode(-10);
root->right = newNode(30);
root->left->right = newNode(8);
root->left->right->left = newNode(6);
root->left->right->right = newNode(9);
root->right->left = newNode(25);
root->right->right = newNode(60);
root->right->right->right = newNode(78);
root->right->left->right = newNode(28);
postorder(root);
return 0;
}