Skip to content

Commit 82273c5

Browse files
authored
Create 987-vertical-order-traversal-of-a-binary-tree.js
1 parent 762c188 commit 82273c5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
* @param {TreeNode} root
11+
* @return {number[][]}
12+
*/
13+
const verticalTraversal = function(root) {
14+
const arr = []
15+
helper(root, 0, 0, arr)
16+
arr.sort((a, b) => a[0] - b[0] || b[1] - a[1] || a[2] - b[2])
17+
const res = new Map()
18+
19+
for(let [x, y, val] of arr) {
20+
if(!res.has(x)) res.set(x, [])
21+
res.get(x).push(val)
22+
}
23+
return [...res.values()]
24+
};
25+
26+
function helper(node, x, y, arr) {
27+
if(node) {
28+
helper(node.left, x - 1, y - 1, arr)
29+
arr.push([x, y, node.val])
30+
helper(node.right, x + 1, y - 1, arr)
31+
}
32+
}

0 commit comments

Comments
 (0)