Skip to content

Commit ad1eed4

Browse files
authored
Create 2458-height-of-binary-tree-after-subtree-removal-queries.js
1 parent dab908a commit ad1eed4

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
* @param {number[]} queries
12+
* @return {number[]}
13+
*/
14+
const treeQueries = function(root, queries) {
15+
const height = [], depth = [], { max } = Math
16+
dfs(root, 0)
17+
18+
function dfs(node, dep) {
19+
if(node == null) return 0
20+
depth[node.val] = dep
21+
const h = max(dfs(node.left, dep + 1), dfs(node.right, dep + 1))
22+
height[node.val] = h
23+
return h + 1
24+
}
25+
// console.log(height, depth)
26+
27+
const neighbors = []
28+
for(let i = 1; i < height.length; i++) {
29+
if(height[i] == null) continue
30+
const d = depth[i]
31+
if(neighbors[d] == null) neighbors[d] = []
32+
neighbors[d].push([height[i], i])
33+
neighbors[d].sort((a, b) => b[0] - a[0])
34+
if(neighbors[d].length > 2) neighbors[d].pop()
35+
}
36+
// console.log(neighbors)
37+
const res = []
38+
for(const q of queries) {
39+
const d = depth[q]
40+
if(neighbors[d].length === 1) res.push(d - 1)
41+
else if(q === neighbors[d][0][1]) {
42+
// console.log('in', d)
43+
res.push(d + neighbors[d][1][0])
44+
} else {
45+
res.push(d + neighbors[d][0][0])
46+
}
47+
}
48+
49+
return res
50+
};

0 commit comments

Comments
 (0)