Skip to content

Commit 81d45a1

Browse files
authored
Update 0103-binary-tree-zigzag-level-order-traversal.js
1 parent 79fd29b commit 81d45a1

File tree

1 file changed

+29
-37
lines changed

1 file changed

+29
-37
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,41 @@
11
/**
2-
* Definition for a binary tree node.
3-
* function TreeNode(val, left, right) {
4-
* this.val = (val===undefined ? 0 : val)
5-
* this.left = (left===undefined ? null : left)
6-
* this.right = (right===undefined ? null : right)
7-
* }
8-
*/
9-
/**
10-
* BFS | LevelOrderTraversal
11-
* Time O(n) | Space O(n)
2+
* BFS
3+
* Time O(N) | Space O(N)
124
* https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
135
* @param {TreeNode} root
146
* @return {number[][]}
157
*/
16-
var zigzagLevelOrder = function(root) {
8+
var zigzagLevelOrder = (root) => {
9+
const isEdgeBase = (root === null);
10+
if (isEdgeBase) return [];
1711

18-
const q = new Queue();
19-
20-
if(root) q.enqueue(root);
21-
22-
let isLeft = true;
23-
24-
const zigzagOrder = [];
12+
return search(root);/* Time O(N) | Space O(N) */
13+
};
2514

26-
while(!q.isEmpty()) {
15+
var search = (root, isZigZag = true, order = []) => {
16+
const queue = new Queue([ root ]);
17+
18+
while (!queue.isEmpty()) { /* Time O(N) */
19+
const levels = [];
2720

28-
let size = q.size();
29-
const row = [];
21+
bfs(queue, isZigZag, levels); /* Time O(WIDTH) | Space O(WIDTH) */
22+
order.push(levels); /* Space O(N) */
23+
isZigZag = !isZigZag;
24+
}
25+
26+
return order;
27+
}
3028

31-
while(size) {
32-
const node = q.dequeue();
33-
row.push(node.val);
34-
if(node.left) q.enqueue(node.left);
35-
if(node.right) q.enqueue(node.right);
36-
size--;
37-
}
29+
const bfs = (queue, isZigZag, levels) => {
30+
for (let level = queue.size(); (0 < level); level--) {/* Time O(WIDTH) */
31+
const { left, val, right } = queue.dequeue();
32+
33+
if (left) queue.enqueue(left); /* Space O(WIDTH) */
34+
if (right) queue.enqueue(right);/* Space O(WIDTH) */
3835

39-
if(!isLeft) {
40-
zigzagOrder.push(row.reverse());
41-
}
42-
if(isLeft) {
43-
zigzagOrder.push(row);
44-
}
45-
isLeft = !isLeft;
36+
levels.push(val); /* Space O(N) */
4637
}
4738

48-
return zigzagOrder;
49-
};
39+
if (!isZigZag) levels.reverse();
40+
}
41+

0 commit comments

Comments
 (0)