Skip to content

Commit 750199e

Browse files
authored
Create 103-binary-tree-zigzag-level-order-traversal.js
1 parent 389d696 commit 750199e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number[][]}
11+
*/
12+
const zigzagLevelOrder = function(root) {
13+
if(root == null) return []
14+
const row = [root]
15+
const res = []
16+
bfs(row, res)
17+
for(let i = 0; i < res.length; i++) {
18+
res[i] = i % 2 === 0 ? res[i] : res[i].reverse()
19+
}
20+
return res
21+
};
22+
23+
function bfs(row, res) {
24+
if(row.length === 0) return
25+
let tmp = []
26+
let next = []
27+
for(let i = 0; i< row.length; i++) {
28+
tmp.push(row[i].val)
29+
if(row[i].left) {
30+
next.push(row[i].left)
31+
}
32+
if(row[i].right) {
33+
next.push(row[i].right)
34+
}
35+
}
36+
if(tmp.length) {
37+
res.push(tmp)
38+
}
39+
bfs(next, res)
40+
}

0 commit comments

Comments
 (0)