|
| 1 | +/** |
| 2 | + * 314. Binary Tree Vertical Order Traversal |
| 3 | + * https://leetcode.com/problems/binary-tree-vertical-order-traversal/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree, return the vertical order traversal of its nodes' values. |
| 7 | + * (i.e., from top to bottom, column by column). |
| 8 | + * |
| 9 | + * If two nodes are in the same row and column, the order should be from left to right. |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * Definition for a binary tree node. |
| 14 | + * function TreeNode(val, left, right) { |
| 15 | + * this.val = (val===undefined ? 0 : val) |
| 16 | + * this.left = (left===undefined ? null : left) |
| 17 | + * this.right = (right===undefined ? null : right) |
| 18 | + * } |
| 19 | + */ |
| 20 | +/** |
| 21 | + * @param {TreeNode} root |
| 22 | + * @return {number[][]} |
| 23 | + */ |
| 24 | +var verticalOrder = function(root) { |
| 25 | + if (!root) return []; |
| 26 | + |
| 27 | + const columns = new Map(); |
| 28 | + const queue = [[root, 0]]; |
| 29 | + let minCol = 0; |
| 30 | + let maxCol = 0; |
| 31 | + |
| 32 | + while (queue.length) { |
| 33 | + const [node, col] = queue.shift(); |
| 34 | + if (!columns.has(col)) columns.set(col, []); |
| 35 | + columns.get(col).push(node.val); |
| 36 | + |
| 37 | + if (node.left) { |
| 38 | + queue.push([node.left, col - 1]); |
| 39 | + minCol = Math.min(minCol, col - 1); |
| 40 | + } |
| 41 | + if (node.right) { |
| 42 | + queue.push([node.right, col + 1]); |
| 43 | + maxCol = Math.max(maxCol, col + 1); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + const result = []; |
| 48 | + for (let col = minCol; col <= maxCol; col++) { |
| 49 | + if (columns.has(col)) result.push(columns.get(col)); |
| 50 | + } |
| 51 | + |
| 52 | + return result; |
| 53 | +}; |
0 commit comments