Skip to content

Commit 145cc0c

Browse files
committed
2
1 parent 521b68d commit 145cc0c

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
13+
// Start typing your C/C++ solution below
14+
// DO NOT write int main() function
15+
16+
vector<vector<int>> result;
17+
if (root == NULL) return result;
18+
19+
stack<TreeNode*> stackNow;
20+
stack<TreeNode*> stackNext;
21+
vector<int> value;
22+
bool left2right = true;
23+
stackNow.push(root);
24+
25+
while (!stackNow.empty()) {
26+
TreeNode *node = stackNow.top();
27+
stackNow.pop();
28+
value.push_back(node->val);
29+
if (left2right) {
30+
if (node->left)
31+
stackNext.push(node->left);
32+
if (node->right)
33+
stackNext.push(node->right);
34+
}
35+
else {
36+
if (node->right)
37+
stackNext.push(node->right);
38+
if (node->left)
39+
stackNext.push(node->left);
40+
}
41+
if (stackNow.empty()) {
42+
result.push_back(value);
43+
value.clear();
44+
left2right = !left2right;
45+
swap(stackNow, stackNext);
46+
}
47+
}
48+
return move(result);
49+
}
50+
};

0 commit comments

Comments
 (0)