-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path32_print_trees_in_zigzag.cc
104 lines (94 loc) · 3.04 KB
/
32_print_trees_in_zigzag.cc
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
#include <iostream>
#include <stack>
#include "tree_util.h"
using namespace std;
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if (!pRoot) {
return res;
}
TreeNode *node;
bool left2right = true;
vector<int> v;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
stack<TreeNode*> *s_cur = &s1;
stack<TreeNode*> *s_next = &s2;
s_cur->push(pRoot);
while (!s_cur->empty() || !s_next->empty()) {
node = s_cur->top();
s_cur->pop();
v.push_back(node->val);
if (left2right) {
if (node->left) {
s_next->push(node->left);
}
if (node->right) {
s_next->push(node->right);
}
} else {
if (node->right) {
s_next->push(node->right);
}
if (node->left) {
s_next->push(node->left);
}
}
if (s_cur->empty()) {
// 当前层打印完毕。
res.push_back(v);
v.clear();
left2right = !left2right;
stack<TreeNode*> *tmp = s_cur;
s_cur = s_next;
s_next = tmp;
}
}
return res;
}
};
int main(int argc, char *argv[])
{
{
int arr[] = { 8, 6, 5, -1, -1, 7, -1, -1, 10, 9, -1, -1, 11, -1, -1 };
TreeNode* root = create_pre_order(arr, NELEM(arr));
pre_order(root);
vector<vector<int> > res = Solution().Print(root);
for (vector<vector<int> >::iterator it = res.begin(); it != res.end(); it++) {
for (vector<int>::iterator it1 = it->begin(); it1 != it->end(); it1++) {
cout << *it1 << " ";
}
cout << endl;
}
delete_postorder(root);
}
{
int arr[] = { 1, 2, 4, 8, -1, -1, 9, -1, -1, 5, 10, -1, -1, 11, -1, -1, 3, 6, 12, -1, -1, 13, -1, -1, 7, 14, -1, -1, 15, -1, -1 };
TreeNode* root = create_pre_order(arr, NELEM(arr));
pre_order(root);
vector<vector<int> > res = Solution().Print(root);
for (vector<vector<int> >::iterator it = res.begin(); it != res.end(); it++) {
for (vector<int>::iterator it1 = it->begin(); it1 != it->end(); it1++) {
cout << *it1 << " ";
}
cout << endl;
}
delete_postorder(root);
}
{
int arr[] = { 1, 2, 3, -1, -1, -1, -1 };
TreeNode* root = create_pre_order(arr, NELEM(arr));
pre_order(root);
vector<vector<int> > res = Solution().Print(root);
for (vector<vector<int> >::iterator it = res.begin(); it != res.end(); it++) {
for (vector<int>::iterator it1 = it->begin(); it1 != it->end(); it1++) {
cout << *it1 << " ";
}
cout << endl;
}
delete_postorder(root);
}
return 0;
}