-
Notifications
You must be signed in to change notification settings - Fork 7
/
103.cpp
47 lines (43 loc) · 1.19 KB
/
103.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
/**
* 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>> res;
deque<TreeNode*> dq;
stack<TreeNode*> st;
bool leftToright = true;
if(root) dq.push_back(root);
vector<int> tp;
while(!dq.empty()){
TreeNode *nd = dq.front();
dq.pop_front();
tp.push_back(nd->val);
if(leftToright){
if(nd->left) st.push(nd->left);
if(nd->right) st.push(nd->right);
}
else{
if(nd->right) st.push(nd->right);
if(nd->left) st.push(nd->left);
}
if(dq.empty()){
res.push_back(tp);
tp.clear();
while(!st.empty()){
dq.push_back(st.top());
st.pop();
}
leftToright = !leftToright;
}
}
return res;
}
};