-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPostorder_of_Tree_Iterative-2_Stack.cpp
77 lines (64 loc) · 1.31 KB
/
Postorder_of_Tree_Iterative-2_Stack.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
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *left, *right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void postorder(struct node* root)
{
if(root == NULL)
return;
stack <node*> s1,s2;
struct node *temp;
s1.push(root);
while(!s1.empty())
{
temp = s1.top();
s1.pop();
s2.push(temp);
if(temp->left)
s1.push(temp->left);
if(temp->right)
s1.push(temp->right);
}
while(!s2.empty())
{
temp = s2.top();
s2.pop();
cout<<temp->data<<" ";
}
}
/*
// Recursive Way:
void postorder(struct node* root)
{
if(root == NULL)
return;
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
*/
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left ->left = newNode(7);
root->right->left ->right = newNode(8);
cout<<"Post-order traversal is : ";
postorder(root);
return 0;
}