Skip to content

Commit 9bb7a48

Browse files
authored
Update 103-binary-tree-zigzag-level-order-traversal.js
1 parent 91d1209 commit 9bb7a48

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

103-binary-tree-zigzag-level-order-traversal.js

+37
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,40 @@ function bfs(row, res) {
3838
}
3939
bfs(next, res)
4040
}
41+
42+
// another
43+
44+
/**
45+
* Definition for a binary tree node.
46+
* function TreeNode(val, left, right) {
47+
* this.val = (val===undefined ? 0 : val)
48+
* this.left = (left===undefined ? null : left)
49+
* this.right = (right===undefined ? null : right)
50+
* }
51+
*/
52+
/**
53+
* @param {TreeNode} root
54+
* @return {number[][]}
55+
*/
56+
const zigzagLevelOrder = function (root) {
57+
if (!root) return [];
58+
const queue = [root];
59+
const zigzag = [];
60+
let numLevels = 1;
61+
while (queue.length > 0) {
62+
const width = queue.length;
63+
const levelTraversal = [];
64+
for (let i = 0; i < width; i++) {
65+
const currentNode = queue.shift();
66+
if (currentNode.right) queue.push(currentNode.right);
67+
if (currentNode.left) queue.push(currentNode.left);
68+
numLevels % 2 === 0
69+
? levelTraversal.push(currentNode.val)
70+
: levelTraversal.unshift(currentNode.val);
71+
}
72+
zigzag.push(levelTraversal);
73+
numLevels++;
74+
}
75+
76+
return zigzag;
77+
};

0 commit comments

Comments
 (0)