forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-zigzag-level-order-traversal-2.cpp
More file actions
33 lines (31 loc) · 1.14 KB
/
Copy pathbinary-tree-zigzag-level-order-traversal-2.cpp
File metadata and controls
33 lines (31 loc) · 1.14 KB
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
// Binary Tree Zigzag Level Order Traversal
// 广度优先遍历,用一个bool记录是从左到右还是从右到左,每一层结束就翻转一下。
// 迭代版,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > result;
queue<TreeNode*> current, next;
bool left_to_right = true;
if(root == nullptr) {
return result;
} else {
current.push(root);
}
while (!current.empty()) {
vector<int> level; // elments in one level
while (!current.empty()) {
TreeNode* node = current.front();
current.pop();
level.push_back(node->val);
if (node->left != nullptr) next.push(node->left);
if (node->right != nullptr) next.push(node->right);
}
if (!left_to_right) reverse(level.begin(), level.end());
result.push_back(level);
left_to_right = !left_to_right;
swap(next, current);
}
return result;
}
};