-
Notifications
You must be signed in to change notification settings - Fork 4
/
103. Binary Tree Zigzag Level Order Traversal
51 lines (42 loc) · 1.37 KB
/
103. Binary Tree Zigzag Level Order Traversal
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map < int, vector < pair <int, int > > > nodes; // level, {horizontal level, value }
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
list < TreeNode * > q;
vector < vector < int > > ans;
if( root == NULL ) return ans;
q.push_back(root);
int isLeft = true;
while(!q.empty()) {
vector < int > tmp;
int levelSize = q.size();
TreeNode* cur;
for( auto it: q) {
tmp.push_back(it->val);
}
if( !isLeft) {
reverse(tmp.begin(), tmp.end());
}
isLeft = !isLeft;
ans.push_back(tmp);
while( levelSize-- ) {
cur = q.front();
q.pop_front();
if( cur->left ) q.push_back(cur->left);
if( cur->right ) q.push_back(cur->right);
}
}
return ans;
}
};