Featured image of post 1483. 树节点的第 K 个祖先

1483. 树节点的第 K 个祖先

题目描述

给你一棵树,树上有 n 个节点,按从 0n-1 编号。树以父节点数组的形式给出,其中 parent[i] 是节点 i 的父节点。树的根节点是编号为 0 的节点。

树节点的第 k 个祖先节点是从该节点到根节点路径上的第 k 个节点。

实现 TreeAncestor 类:

  • TreeAncestor(int n, int[] parent) 对树和父数组中的节点数初始化对象。
  • getKthAncestor``(int node, int k) 返回节点 node 的第 k 个祖先节点。如果不存在这样的祖先节点,返回 -1 。

示例 1:

  • 输入:

    • [“TreeAncestor”,“getKthAncestor”,“getKthAncestor”,“getKthAncestor”]
    • [[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]
  • 输出: [null,1,0,-1]

  • 解释:

    • TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);
    • treeAncestor.getKthAncestor(3, 1); // 返回 1 ,它是 3 的父节点
    • treeAncestor.getKthAncestor(5, 2); // 返回 0 ,它是 5 的祖父节点
    • treeAncestor.getKthAncestor(6, 3); // 返回 -1 因为不存在满足要求的祖先节点

提示:

  • 1 <= k <= n <= 5 * 104
  • parent[0] == -1 表示编号为 0 的节点是根节点。
  • 对于所有的 0 < i < n0 <= parent[i] < n 总成立
  • 0 <= node < n
  • 至多查询 5 * 104

解法一:动态规划

 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
const Log = 16

type TreeAncestor struct {
    ancestor [][Log]int
}

func Constructor(n int, parent []int) TreeAncestor {
    ret := TreeAncestor{}
    ancestors := make([][Log]int, n)
    for i := 0; i < len(parent); i++ {
        ancestors[i][0] = parent[i]
    }
    for j := 1; j < Log; j++ {
        for i := 0; i < n; i++ {
            if ancestors[i][j-1] != -1 {
                ancestors[i][j] = ancestors[ancestors[i][j-1]][j-1]
            } else {
                ancestors[i][j] = -1
            }
        }
    }
    ret.ancestor = ancestors
    return ret
}

func (this *TreeAncestor) GetKthAncestor(node int, k int) int {
    j := 0
    for k > 0 {
        if k&1 == 1 {
            node = this.ancestor[node][j]
            if node == -1 {
                return -1
            }
        }
        k >>= 1
        j++
    }
    return node
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/12 11:08:38
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计