-
Notifications
You must be signed in to change notification settings - Fork 160
/
PreInPostorder travel of bT with stack.cpp
124 lines (85 loc) · 1.95 KB
/
PreInPostorder travel of bT with 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
114
115
116
117
118
119
120
121
122
123
/*
Iterative Preorder, Inorder, Postorder traversal of binary tree
*/
/*
solution: use stack
O(n) time, O(n) space
*/
#include<cstdlib>
#include <cassert>
#include<stack>
#include<iostream>
using namespace std;
struct NODE {
int val;
NODE* pLft;
NODE* pRgt;
NODE(int n) : val(n), pLft(NULL), pRgt(NULL) {}
};
//postorder
void PostOrderTravel(NODE* root) {
assert(root);
stack<NODE*> stk;
NODE* cur = root;
while (cur != NULL) {
stk.push(cur);
cur = cur->pLft;
}
NODE* prev = NULL;
while (!stk.empty()) {
NODE* tmp = stk.top();
if (tmp->pRgt != NULL && prev != tmp->pRgt) {
NODE* iter = tmp->pRgt;
while (iter != NULL) {
stk.push(iter);
iter = iter->pLft;
}
} else {
cout<<tmp->val<<endl;
prev = tmp;
stk.pop();
}
}
}
//preorder
void PrevOrderTravel(NODE* root) {
assert(root);
stack<NODE*> stk;
stk.push(root);
while (!stk.empty()) {
NODE* top = stk.top();
stk.pop();
cout<<top->val<<endl;
if (top->pRgt != NULL) stk.push(top->pRgt);
if (top->pLft != NULL) stk.push(top->pLft);
}
}
//inorder
void InOrderTravel(NODE* root) {
assert(root);
stack<NODE*> stk;
NODE* cur = root;
while (cur!=NULL) {
stk.push(cur);
cur = cur->pLft;
}
while (!stk.empty()) {
cur = stk.top();
cout<<cur->val<<endl;
stk.pop();
cur = cur->pRgt;
while (cur!=NULL) {
stk.push(cur);
cur = cur->pLft;
}
}
}
int main(){
NODE *head = new NODE(2);
head->pLft = new NODE(1);
head->pRgt = new NODE(3);
PrevOrderTravel(head);
InOrderTravel(head);
PostOrderTravel(head);
return 0;
}