Skip to content

Commit 48830a5

Browse files
committed
Add solution #314
1 parent 18afb13 commit 48830a5

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@
302302
311|[Sparse Matrix Multiplication](./solutions/0311-sparse-matrix-multiplication.js)|Medium|
303303
312|[Burst Balloons](./solutions/0312-burst-balloons.js)|Hard|
304304
313|[Super Ugly Number](./solutions/0313-super-ugly-number.js)|Medium|
305+
314|[Binary Tree Vertical Order Traversal](./solutions/0314-binary-tree-vertical-order-traversal.js)|Medium|
305306
315|[Count of Smaller Numbers After Self](./solutions/0315-count-of-smaller-numbers-after-self.js)|Hard|
306307
316|[Remove Duplicate Letters](./solutions/0316-remove-duplicate-letters.js)|Medium|
307308
318|[Maximum Product of Word Lengths](./solutions/0318-maximum-product-of-word-lengths.js)|Medium|
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

Comments
 (0)