|
| 1 | +/** |
| 2 | + * 1483. Kth Ancestor of a Tree Node |
| 3 | + * https://leetcode.com/problems/kth-ancestor-of-a-tree-node/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array |
| 7 | + * parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the |
| 8 | + * kth ancestor of a given node. |
| 9 | + * |
| 10 | + * The kth ancestor of a tree node is the kth node in the path from that node to the root node. |
| 11 | + * |
| 12 | + * Implement the TreeAncestor class: |
| 13 | + * - TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree |
| 14 | + * and the parent array. |
| 15 | + * - int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there |
| 16 | + * is no such ancestor, return -1. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} n |
| 21 | + * @param {number[]} parent |
| 22 | + */ |
| 23 | +var TreeAncestor = function(n, parent) { |
| 24 | + const maxDepth = Math.ceil(Math.log2(n)); |
| 25 | + this.ancestors = Array.from({ length: n }, () => new Array(maxDepth + 1).fill(-1)); |
| 26 | + |
| 27 | + for (let i = 0; i < n; i++) { |
| 28 | + this.ancestors[i][0] = parent[i]; |
| 29 | + } |
| 30 | + |
| 31 | + for (let j = 1; j <= maxDepth; j++) { |
| 32 | + for (let i = 0; i < n; i++) { |
| 33 | + if (this.ancestors[i][j - 1] !== -1) { |
| 34 | + this.ancestors[i][j] = this.ancestors[this.ancestors[i][j - 1]][j - 1]; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * @param {number} node |
| 42 | + * @param {number} k |
| 43 | + * @return {number} |
| 44 | + */ |
| 45 | +TreeAncestor.prototype.getKthAncestor = function(node, k) { |
| 46 | + let current = node; |
| 47 | + for (let j = 0; k > 0 && current !== -1; j++, k >>= 1) { |
| 48 | + if (k & 1) { |
| 49 | + current = this.ancestors[current][j]; |
| 50 | + } |
| 51 | + } |
| 52 | + return current; |
| 53 | +}; |
0 commit comments