-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack preorder, postorder.cpp
89 lines (77 loc) · 2.09 KB
/
stack preorder, postorder.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
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int val = -1;
TreeNode *leftChild = nullptr, *rightChild = nullptr;
};
TreeNode *root;
TreeNode nodePool[10];
void initTree() {
int idx = 1;
TreeNode *rootNode = &nodePool[idx];
rootNode->val = idx;
root = rootNode;
while (idx < 4) {
TreeNode *leftChild = &nodePool[idx*2];
TreeNode *rightChild = &nodePool[idx*2 + 1];
leftChild->val = idx*2;
rightChild->val = idx*2 + 1;
nodePool[idx].leftChild = leftChild;
nodePool[idx].rightChild = rightChild;
idx++;
}
}
// root을 1등으로, 꼴지로
void traversalPreOrder() {
printf("========== traversalPreOrder ==========\n");
stack<TreeNode*> st;
TreeNode *nodeNow = root;
while (1) {
while (nodeNow != nullptr) {
printf("PreOrder val : %d\n", nodeNow->val);
st.push(nodeNow);
nodeNow = nodeNow->leftChild;
}
if (st.empty()) {
break;
}
nodeNow = st.top();
st.pop();
nodeNow = nodeNow->rightChild;
}
printf("\n");
}
void traversalPostOrder() {
printf("========== traversalPostOrder ==========\n");
stack<TreeNode*> st;
TreeNode *nodeNow = root;
while (1) {
while (nodeNow) {
st.push(nodeNow);
// 왼쪽 자식을 전부 넣어 준다.
nodeNow = nodeNow->leftChild;
}
if (st.empty()) {
break;
}
nodeNow = st.top();
st.pop();
if (nodeNow != nullptr && nodeNow->rightChild != nullptr) {
// 오른쪽 자식이 있다면 일단 현재 노드 데이터를 스택에 넣는다.
TreeNode *mockNode = new TreeNode();
mockNode->val = nodeNow->val;
st.push(mockNode);
} else {
printf("PostOrder val : %d\n", nodeNow->val);
}
nodeNow = nodeNow->rightChild;
}
printf("\n");
}
int main() {
// PreOrder PostOrder 테스트
initTree();
traversalPreOrder();
traversalPostOrder();
}