-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-zigzag-level-order-traversal.cpp
47 lines (47 loc) · 1.38 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define VI vector<int>
#define VII vector<VI >
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
VII result;
if (root == nullptr)
return result;
deque<TreeNode *> cur;
cur.push_back(root);
bool leftToRight = true;
while (!cur.empty()) {
VI levelVal;
deque<TreeNode *> next;
while (!cur.empty()) {
TreeNode *front = cur.front();
levelVal.push_back(front->val);
if (leftToRight) {
if (front->left)
next.push_front(front->left);
if (front->right)
next.push_front(front->right);
}
else {
if (front->right)
next.push_front(front->right);
if (front->left)
next.push_front(front->left);
}
cur.pop_front();
}
result.push_back(levelVal);
cur = next;
leftToRight = !leftToRight;
}
return result;
}
};