arrays - 在给定父数组的情况下查找树的深度

标签 arrays algorithm tree

给出父数组 P,其中 P[i] 表示树中第 i 个节点的父节点(树是通用的)。 root 的父级用 -1 表示。我需要找到树的高度/深度。

示例:P = {-1,0,1,6,6,0,0,2,7}。所以 P[1] = 0 表示节点 1 的父节点为 0 等等。

我的方法:

1. Sort P in O(nlogn). This gives P = {-1,0,0,0,1,2,6,6,7}
2. Scan through the array. 
   If a change is observed on going from index i to i+1 then increment depth (depth++).
   eg When going from index 3 to index 4 of sorted P, there is a change from 0 to 1. So increment depth.
   This scanning takes O(n) time
3. depth - 1 is the depth of the tree.

这种方法似乎适用于我尝试过的示例,但我不确定我是否遗漏了它可能会失败的情况。有人可以提供一个反例吗?谢谢

最佳答案

这是不正确的。考虑两个数组:{-1, 0, 0, 1, 1} 和 {-1, 0, 0, 1, 2}。它们变化的次数不同,但这两棵树的高度相同。

关于arrays - 在给定父数组的情况下查找树的深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24227379/

相关文章:

arrays - 如何部分初始化结构的嵌套元素

ruby - 如何将值添加到数组中的所有先前值

arrays - 在优于 O(N*M) 的时间内找到数组中多个区间的最小元素

algorithm - 搜索查询分词器

c - C 中的进程树层次结构

c - main 中的 next 函数和数组的结果是什么?

javascript - 运行初始数组后,Jquery 数组返回未定义

java - 我们怎样才能得到在一定范围内,int能被2整除的最大次数

识别树是否是其他树的子树的算法

Java 节点交换