Skip to content

Commit f540801

Browse files
authored
add zigzagLevelOrder traversal in binary tree (#14)
1 parent 06cfcb9 commit f540801

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

Diff for: JavaScript/Binary-Tree-ZigZag-Traversal.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Binary Tree ZigZag level Order Traversal
3+
* Medium
4+
*
5+
6+
Example 1:
7+
8+
Given a binary tree, return the zigzag level order traversal of its nodes' values.
9+
(ie, from left to right, then right to left for the next level and alternate between).
10+
11+
For example:
12+
Given binary tree [3,9,20,null,null,15,7],
13+
14+
3
15+
/ \
16+
9 20
17+
/ \
18+
15 7
19+
20+
return its zigzag level order traversal as:
21+
22+
[
23+
[3],
24+
[20,9],
25+
[15,7]
26+
]
27+
28+
* Logic : Using Breadth First Search to Solve This Problem.
29+
Using a boolean to push in front of array and in end of the array and toogle it after every level traversed
30+
* Runtime: 80 ms
31+
* Memory Usage: 37.6 MB
32+
*
33+
*/
34+
35+
var zigzagLevelOrder = function (root) {
36+
let queue = [],
37+
result = [],
38+
zigzag = true;
39+
if (root == null) return [];
40+
queue.push(root);
41+
while (queue.length) {
42+
let size = queue.length;
43+
let temp = [];
44+
while (size--) {
45+
let pop = queue.shift();
46+
if (pop && pop.left) queue.push(pop.left);
47+
if (pop && pop.right) queue.push(pop.right);
48+
if (zigzag) {
49+
if (pop) temp.push(pop.val);
50+
} else {
51+
if (pop) temp.unshift(pop.val);
52+
}
53+
}
54+
zigzag = !zigzag;
55+
result.push(temp);
56+
}
57+
58+
return result;
59+
};

Diff for: README.md

+12
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,18 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
123123
</div>
124124
<br/>
125125

126+
## Tree
127+
128+
| # | Title | Solution | Time | Space | Difficulty | Tag | Note |
129+
| --- | --------------------------------------------------------------------- | ----------------------------------------- | ------ | ------ | ---------- | ----- | ---- |
130+
| 103 | [ZigZag Level Order](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) | [JavaScript](./JavaScript/Binary-Tree-ZigZag-Traversal.js) | _O(n)_ | _O(n)_ | Medium | Binary Tree | |
131+
132+
<br/>
133+
<div align="right">
134+
<b><a href="#algorithms">⬆️ Back to Top</a></b>
135+
</div>
136+
<br/>
137+
126138
## Hash Table
127139

128140
| # | Title | Solution | Time | Space | Difficulty | Tag | Note |

0 commit comments

Comments
 (0)