forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
54 lines (51 loc) · 1.33 KB
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function verticalTraversal(root: TreeNode | null): number[][] {
let solution = [];
dfs(root, 0, 0, solution);
solution.sort(compare);
let ans = [];
let pre = Number.MIN_SAFE_INTEGER;
for (let node of solution) {
const [val, , idx] = node;
if (idx != pre) {
ans.push([]);
pre = idx;
}
ans[ans.length - 1].push(val);
}
return ans;
}
function compare(a: Array<number>, b: Array<number>) {
const [a0, a1, a2] = a,
[b0, b1, b2] = b;
if (a2 == b2) {
if (a1 == b1) {
return a0 - b0;
}
return a1 - b1;
}
return a2 - b2;
}
function dfs(
root: TreeNode | null,
depth: number,
idx: number,
solution: Array<Array<number>>
) {
if (!root) return;
solution.push([root.val, depth, idx]);
dfs(root.left, depth + 1, idx - 1, solution);
dfs(root.right, depth + 1, idx + 1, solution);
}