|
1 | 1 | /**
|
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) |
12 | 4 | * https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
|
13 | 5 | * @param {TreeNode} root
|
14 | 6 | * @return {number[][]}
|
15 | 7 | */
|
16 |
| -var zigzagLevelOrder = function(root) { |
| 8 | +var zigzagLevelOrder = (root) => { |
| 9 | + const isEdgeBase = (root === null); |
| 10 | + if (isEdgeBase) return []; |
17 | 11 |
|
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 | +}; |
25 | 14 |
|
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 = []; |
27 | 20 |
|
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 | +} |
30 | 28 |
|
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) */ |
38 | 35 |
|
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) */ |
46 | 37 | }
|
47 | 38 |
|
48 |
| - return zigzagOrder; |
49 |
| -}; |
| 39 | + if (!isZigZag) levels.reverse(); |
| 40 | +} |
| 41 | + |
0 commit comments