-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetCode_103_40.cpp
More file actions
53 lines (50 loc) · 1.28 KB
/
LeetCode_103_40.cpp
File metadata and controls
53 lines (50 loc) · 1.28 KB
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
/*
* @lc app=leetcode id=103 lang=cpp
*
* [103] Binary Tree Zigzag Level Order Traversal
*/
/**
* 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) {
vector<vector<int>> result;
queue<TreeNode*> q;
bool zig = true; /*left then right on true*/
q.push(root);
stack<int> s;
while(!q.empty() && root)
{
vector<int> vec;
int cnt = q.size();
while(cnt > 0)
{
TreeNode* node = q.front();
q.pop();
if(node)
{
if(zig) vec.push_back(node->val);
else s.push(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
cnt--;
}
zig = !zig;
while(!s.empty())
{
vec.push_back(s.top());
s.pop();
}
result.push_back(vec);
}
return result;
}
};