forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Tree_Zigzag_Level_Order_Traversal.cc
59 lines (59 loc) · 1.64 KB
/
Binary_Tree_Zigzag_Level_Order_Traversal.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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > ans;
if (root == NULL) {
return ans;
}
queue<TreeNode *> q;
queue<int> dep_que;
vector<int> tmp;
q.push(root);
dep_que.push(1);
TreeNode *cntNode = NULL;
int cntDepth, minDepth = 1;
bool flag = false;
while (!q.empty()) {
cntNode = q.front();
q.pop();
cntDepth = dep_que.front();
dep_que.pop();
if (cntDepth > minDepth) {
minDepth = cntDepth;
if (flag) {
reverse(tmp.begin(), tmp.end());
}
flag = !flag;
ans.push_back(tmp);
tmp.clear();
}
tmp.push_back(cntNode->val);
if (cntNode->left) {
q.push(cntNode->left);
dep_que.push(cntDepth + 1);
}
if (cntNode->right) {
q.push(cntNode->right);
dep_que.push(cntDepth + 1);
}
}
if (tmp.size() > 0) {
if (flag) {
reverse(tmp.begin(), tmp.end());
}
ans.push_back(tmp);
}
return ans;
}
};