Skip to content

Commit 191aa10

Browse files
committedDec 19, 2020
Merge branch 'main' of github.com:doocs/leetcode into main
2 parents 11034f0 + 02b4e6b commit 191aa10

File tree

1 file changed

+33
-0
lines changed
  • solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal

1 file changed

+33
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
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+
if (!root) return {};
14+
vector<vector<int>> res;
15+
queue<TreeNode*> q{{root}};
16+
bool leftToRight = true;
17+
while (!q.empty()) {
18+
int size = q.size();
19+
vector<int> oneLevel(size);
20+
for (int i = 0; i < size; ++i) {
21+
TreeNode* t = q.front();
22+
q.pop();
23+
int idx = leftToRight ? i : (size - 1 - i);
24+
oneLevel[idx] = t->val;
25+
if (t->left) q.push(t->left);
26+
if (t->right) q.push(t->right);
27+
}
28+
leftToRight = !leftToRight;
29+
res.push_back(oneLevel);
30+
}
31+
return res;
32+
}
33+
};

0 commit comments

Comments
 (0)