-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path103-Binary Tree Zigzag Level Order Traversal (O(n) BFS).cpp
55 lines (55 loc) · 1.42 KB
/
103-Binary Tree Zigzag Level Order Traversal (O(n) BFS).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
/**
* Definition for a binary tree node.
* 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)
{
if(!root)
return {};
vector<vector<int>> result;
int depth=0;
vector<TreeNode*> q;
q.push_back(root);
while(!q.empty())
{
vector<TreeNode*> temp;
if(depth&1)
{
for(int i=q.size()-1;i>=0;i--)
{
if(result.size()==depth)
result.push_back({q[i]->val});
else
result[depth].push_back(q[i]->val);
}
}
else
{
for(int i=0;i<q.size();i++)
{
if(result.size()==depth)
result.push_back({q[i]->val});
else
result[depth].push_back(q[i]->val);
}
}
for(int i=0;i<q.size();i++)
{
if(q[i]->left)
temp.push_back(q[i]->left);
if(q[i]->right)
temp.push_back(q[i]->right);
}
q.swap(temp);
depth++;
}
return result;
}
};