|
| 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 depth = [], height = [], depthHash = [] |
| 16 | + dfs(root, 0) |
| 17 | + const res = [] |
| 18 | + for(const e of queries) { |
| 19 | + const d = depth[e], h = height[e], row = depthHash[d] |
| 20 | + if(row.length === 1) { |
| 21 | + res.push(d - 1) |
| 22 | + } else if(h === row[0]) { |
| 23 | + res.push(d + row[1]) |
| 24 | + } else { |
| 25 | + res.push(d + row[0]) |
| 26 | + } |
| 27 | + } |
| 28 | + return res |
| 29 | + |
| 30 | + function dfs(node, d) { |
| 31 | + if(node == null) return 0 |
| 32 | + const {val} = node |
| 33 | + const h = Math.max(dfs(node.left, d + 1), dfs(node.right, d + 1)) |
| 34 | + depth[val] = d |
| 35 | + height[val] = h |
| 36 | + if(depthHash[d] == null) depthHash[d] = [] |
| 37 | + depthHash[d].push(h) |
| 38 | + keepLargestTwo(depthHash[d]) |
| 39 | + return h + 1 |
| 40 | + } |
| 41 | + function keepLargestTwo(arr) { |
| 42 | + arr.sort((a,b) => b - a) |
| 43 | + if(arr.length > 2) { |
| 44 | + arr.splice(2, arr.length - 2) |
| 45 | + } |
| 46 | + } |
| 47 | +}; |
| 48 | + |
| 49 | +// another |
| 50 | + |
| 51 | + |
1 | 52 | /**
|
2 | 53 | * Definition for a binary tree node.
|
3 | 54 | * function TreeNode(val, left, right) {
|
|
0 commit comments