Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 树节点挑战的第k个祖先_Python_Python 3.x_Tree_Dynamic Programming - Fatal编程技术网

Python 树节点挑战的第k个祖先

Python 树节点挑战的第k个祖先,python,python-3.x,tree,dynamic-programming,Python,Python 3.x,Tree,Dynamic Programming,挑战如下: 您将看到一棵树,其中有n个节点,编号从0到n-1,形式为 父数组,其中父[i]是节点i的父。树根 是节点0 实现函数getKthAncestor(intnode,intk)以返回第k个 给定节点的祖先。如果没有这样的祖先,返回-1 树节点的第k个祖先是该节点路径中的第k个节点 节点到根 例如: 输入: ["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"] [[7,[-1,0,0,1,1,2,2]],[3

挑战如下:

您将看到一棵树,其中有n个节点,编号从0到n-1,形式为 父数组,其中父[i]是节点i的父。树根 是节点0

实现函数getKthAncestor(intnode,intk)以返回第k个 给定节点的祖先。如果没有这样的祖先,返回-1

树节点的第k个祖先是该节点路径中的第k个节点 节点到根

例如:

输入:

["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);  // returns 1 which is the parent of 3
treeAncestor.getKthAncestor(5, 2);  // returns 0 which is the grandparent of 5
treeAncestor.getKthAncestor(6, 3);  // returns -1 because there is no such ancestor
限制条件:

1 <= k <= n <= 5*10^4
parent[0] == -1 indicating that 0 is the root node.
0 <= parent[i] < n for all 0 < i < n
0 <= node < n
There will be at most 5*10^4 queries.

哇。这是一个很酷的解决方案

解决方案基于两个想法:

  • 在构建期间构建祖先矩阵(
    self.pars
  • 将祖先图分解为大小为1、2、4、8等(2^n)的步骤
self.pars
是一个矩阵,其中行号
n
表示行中第i个元素的2^n祖先(n从0开始)。例如,在第3行中,我们将拥有树中节点中所有元素的第8个祖先

然后在查询时,该算法将请求分解为一系列日志(k)步骤,以获取节点的第k个祖先。每一步都是k的二进制表示中的一个数字

例如,考虑k=6。9的二进制表示为1-1-0:

  • 数字0(最后一个)是0,所以什么也不要做
  • 数字1是1。2^1是2,所以获取我们正在查看的节点的第二个祖先
  • 数字2也是1。2^2是4,因此获取当前节点的第四个祖先

我们完成了-分3步,我们一路到达目标节点

我想为我花了一些时间(还有一些打印语句)才理解的部分,即
self.pars
构建过程,添加一些解释。没有明显的步骤1、2、4、8系列。父项列表允许查找父项,即在路径中执行一步。如果我们将列表应用于自身,我们将有一个包含2个步骤(1+1)的列表。但是,当我们对新列表执行相同操作时,我们将没有3个步骤,而是4个步骤(2+2)。然后4+4等等,MahdeenSkyYT-这回答了你的问题吗?这是一个众所周知的问题,解决方案使用稀疏表和二进制提升,