/** * @param {TreeNode} root * @return {number[][]} */ var verticalOrder = function (root) { let res = []; // corner case if (root == null) { return res; }
// normal case let map = newMap(); let queue = []; queue.push([root, 0]); let min = 0; let max = 0; while (queue.length > 0) { let cur = queue.shift(); let node = cur[0]; let col = cur[1]; if (!map.has(col)) { map.set(col, []); } map.get(col).push(node.val); if (node.left) { queue.push([node.left, col - 1]); min = Math.min(min, col - 1); } if (node.right) { queue.push([node.right, col + 1]); max = Math.max(max, col + 1); } }
for (let i = min; i <= max; i++) { res.push(map.get(i)); } return res; };
相关题目
1 2
314. Binary Tree Vertical Order Traversal 987. Vertical Order Traversal of a Binary Tree