【发布时间】:2014-06-15 07:14:34
【问题描述】:
给定一个父数组 P,其中 P[i] 表示树中第 i 个节点的父节点(树是通用的)。根的父级用 -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.
这种方法似乎适用于我尝试过的示例,但我不确定我是否错过了可能失败的案例。有人可以提供一个反例吗?谢谢
【问题讨论】:
-
提示另一种方法:看看你是否可以创建一个函数 depth(),它将单个节点索引作为参数并告诉你该节点的深度。它将使用递归,如果在每个节点的循环中调用它需要 O(n^2) 时间(这是确定整体树高所必需的)。现在如何消除递归,将循环的总时间减少到 O(n)?