-
Notifications
You must be signed in to change notification settings - Fork 1
/
Postorder_of_Tree_Iterative-1_Stack.cpp
113 lines (97 loc) · 2.06 KB
/
Postorder_of_Tree_Iterative-1_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
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
#include <bits/stdc++.h>
using namespace std;
#define MAX_SIZE 100
struct Node
{
int data;
struct Node *left, *right;
};
struct Stack
{
int size;
int top;
struct Node* *array;
};
struct Node* newNode(int data)
{
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
struct Stack* createStack(int size)
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
stack->size = size;
stack->top = -1;
stack->array = (struct Node**) malloc(stack->size * sizeof(struct Node*));
return stack;
}
int isFull(struct Stack* stack)
{
return stack->top - 1 == stack->size;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
void push(struct Stack* stack, struct Node* node)
{
if (isFull(stack))
return;
stack->array[++stack->top] = node;
}
struct Node* pop(struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top--];
}
struct Node* peek(struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top];
}
void postorder(struct Node* root)
{
if (root == NULL)
return;
struct Stack* stack = createStack(MAX_SIZE);
do
{
while (root)
{
if (root->right)
push(stack, root->right);
push(stack, root);
root = root->left;
}
root = pop(stack);
if (root->right && peek(stack) == root->right)
{
pop(stack);
push(stack, root);
root = root->right;
}
else
{
cout<<root->data<<" ";
root = NULL;
}
}
while (!isEmpty(stack));
}
int main()
{
struct Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
postorder(root);
return 0;
}