Skip to content

Commit d88f4fc

Browse files
authored
Create 0103-binary-tree-zigzag-level-order-traversal.cpp
1 parent 4fd1e72 commit d88f4fc

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.
3+
(i.e., from left to right, then right to left for the next level and alternate between).
4+
5+
Ex. Input: root = [3,9,20,null,null,15,7]
6+
Output: [[3],[20,9],[15,7]]
7+
8+
Time : O(N)
9+
Space : O(N)
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* struct TreeNode {
15+
* int val;
16+
* TreeNode *left;
17+
* TreeNode *right;
18+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
19+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
20+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
21+
* };
22+
*/
23+
class Solution {
24+
public:
25+
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
26+
vector <vector <int>> v;
27+
if(root == NULL)
28+
return v;
29+
30+
queue <TreeNode *> q;
31+
q.push(root);
32+
bool changeDirection = true;
33+
34+
while(!q.empty()) {
35+
vector <int> v1;
36+
int siz = q.size();
37+
38+
for(int i = 0 ; i < siz ; i++) {
39+
if(changeDirection)
40+
v1.push_back(q.front() -> val);
41+
else
42+
v1.insert(v1.begin(), q.front() -> val);
43+
44+
if(q.front() -> left != NULL)
45+
q.push(q.front() -> left);
46+
if(q.front() -> right != NULL)
47+
q.push(q.front() -> right);
48+
49+
q.pop();
50+
}
51+
changeDirection = !changeDirection;
52+
v.push_back(v1);
53+
}
54+
return v;
55+
}
56+
};

0 commit comments

Comments
 (0)