-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Tree_Zigzag_Level_Order_Traversal.cpp
59 lines (52 loc) · 1.53 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
// Given a binary tree, return the zigzag level order traversal of its nodes' values.
// (ie, from left to right, then right to left for the next level and alternate between)
// For example:
// Given binary tree {3,9,20,#,#,15,7},
// 3
// / \
// 9 20
// / \
// 15 7
// return its zigzag level order traversal as:
// [
// [3],
// [20,9],
// [15,7]
// ]
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > result;
vector<int> level;
if (root == NULL)
return result;
queue<TreeNode*> nodes;
nodes.push(root);
nodes.push(NULL);
while (!nodes.empty()) {
TreeNode *current = nodes.front();
nodes.pop();
if (current == NULL) {
result.push_back(level);
level.clear();
if (nodes.empty())
break;
nodes.push(NULL);
}
else {
level.push_back(current->val);
if (current->left != NULL)
nodes.push(current->left);
if (current->right != NULL)
nodes.push(current->right);
}
}
// reverse the order of odd index level vectors
for (int i = 1; i < result.size(); i += 2) {
vector<int> temp(result[i]);
result[i].clear();
result[i].insert(result[i].end(), temp.rbegin(), temp.rend());
}
return result;
}
};