-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary-tree-zigzag-level-order-traversal.cpp
107 lines (98 loc) · 2.96 KB
/
binary-tree-zigzag-level-order-traversal.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
// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
// Using stack.
class Solution {
/**
* @param root: The root of binary tree.
* @return: A list of lists of integer include
* the zigzag level order traversal of its nodes' values
*/
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> result;
stack<TreeNode *> current_level;
if (root != nullptr) {
current_level.emplace(root);
}
bool normal_order = true;
while (!current_level.empty()) {
vector<int> level;
stack<TreeNode *> next_level;
int size = current_level.size();
while (!current_level.empty()) {
auto *top = current_level.top();
current_level.pop();
level.emplace_back(top->val);
if (normal_order) {
if (top->left != nullptr) {
next_level.emplace(top->left);
}
if (top->right != nullptr) {
next_level.emplace(top->right);
}
} else {
if (top->right != nullptr) {
next_level.emplace(top->right);
}
if (top->left != nullptr) {
next_level.emplace(top->left);
}
}
}
result.emplace_back(move(level));
normal_order = !normal_order;
swap(current_level, next_level);
}
return result;
}
};
// Useing queue.
class Solution2 {
/**
* @param root: The root of binary tree.
* @return: A list of lists of integer include
* the zigzag level order traversal of its nodes' values
*/
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> result;
queue<TreeNode *> que;
if (root != nullptr) {
que.emplace(root);
}
bool normal_order = true;
while (!que.empty()) {
vector<int> level;
int size = que.size();
for (int i = 0; i < size; i++) {
auto *front = que.front();
que.pop();
level.emplace_back(front->val);
if (front->left != nullptr) {
que.emplace(front->left);
}
if (front->right != nullptr) {
que.emplace(front->right);
}
}
if (!normal_order) {
reverse(level.begin(), level.end());
}
result.emplace_back(move(level));
normal_order = !normal_order;
}
return result;
}
};