-
Notifications
You must be signed in to change notification settings - Fork 42
/
solution.ts
67 lines (64 loc) · 1.72 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
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* 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 findClosestLeaf (root: TreeNode | null, k: number): number {
if (!root) {
return 0;
}
const path:TreeNode[] = [];
function findPath (root:TreeNode) {
path.push(root);
if (root.val === k) {
return true;
}
if (root.left) {
const rstL = findPath(root.left);
if (rstL) {
return true;
}
}
if (root.right) {
const rstR = findPath(root.right);
if (rstR) {
return true;
}
}
path.pop();
return false;
}
findPath(root);
let result = 0;
let minDis = Infinity;
function findLeaf (root:TreeNode|null, dis:number) {
if (!root || dis >= minDis) {
return;
}
if (!root.left && !root.right) {
result = root.val;
minDis = dis;
return;
}
dis++;
root.left && findLeaf(root.left, dis);
root.right && findLeaf(root.right, dis);
}
findLeaf(path[path.length - 1], 0);
for (let i = path.length - 2; i > -1; i--) {
if (path[i + 1] === path[i].left) {
findLeaf(path[i].right, path.length - i);
} else {
findLeaf(path[i].left, path.length - i);
}
}
return result;
}