. - 力扣(LeetCode)
给你一棵树,树上有 n 个节点,按从 0 到 n-1 编号。树以父节点数组的形式给出,其中 parent[i] 是节点 i 的父节点。树的根节点是编号为 0 的节点。
树节点的第 k 个祖先节点是从该节点到根节点路径上的第 k 个节点。
实现 TreeAncestor 类:
- TreeAncestor(int n, int[] parent)对树和父数组中的节点数初始化对象。
- getKthAncestor- (int node, int k)返回节点- node的第- k个祖先节点。如果不存在这样的祖先节点,返回- -1。
暴力逐层向上找会卡时间。
class TreeAncestor {
public:constexpr static int Log = 16;vector<vector<int>> ancestors;TreeAncestor(int n, vector<int>& parent) {ancestors = vector<vector<int>>(n, vector<int>(Log, -1));for (int i = 0; i < n; i++) {ancestors[i][0] = parent[i];}for (int j = 1; j < Log; j++) {for (int i = 0; i < n; i++) {if (ancestors[i][j - 1] != -1) {ancestors[i][j] = ancestors[ancestors[i][j - 1]][j - 1];}}}            }int getKthAncestor(int node, int k) {for (int j = 0; j < Log; j++) {if ((k >> j) & 1) {node = ancestors[node][j];if (node == -1) {return -1;}}}return node;}
};
思路:ancestors[i][j]表示第i个节点的第2的k次方个祖先。
思路类似于动态规划,ancestors[i][0]即2的0次方,即第一个 祖先,parent[i];
对于其他,
查询时,因为是表示2的j次方个祖先,所以对于当前k,需逐位判断。