BST中节点的深度包括重复

时间:2012-11-15 06:20:44

标签: java binary-tree depth

我已经实现了一个函数来查找二叉搜索树中节点的深度,但是我的实现没有处理重复。我在下面有我的代码,并想了解如何在此函数中考虑重复案例的一些建议。 WOuld真的很感谢你的帮助。

public int depth(Node n) {
    int result=0;
    if(n == null || n == getRoot())
        return 0;

    return (result = depth(getRoot(), n, result));
}
public int depth(Node temp, Node n, int result) {
    int cmp = n.getData().compareTo(temp.getData());

    if(cmp == 0) {
        int x = result;
        return x;
    }
    else if(cmp < 0) {
            return depth(temp.getLeftChild(), n, ++result);
        }
        else {
            return depth(temp.getRightChild(), n, ++result);
        }                   
}

2 个答案:

答案 0 :(得分:0)

好吧,如果有重复,那么具有给定值的节点的深度本身没有任何意义,因为可能有多个节点具有该值,因此有多个深度。

必须决定它的意思,这可能是(不一定是详尽的清单):

  • 具有该值的最深节点的深度。
  • 具有该值的最浅节点的深度。
  • 使用该值找到的第一个节点的深度。
  • 具有该值的所有节点的平均深度。
  • 具有该值的所有节点的深度范围(最小/最大)。
  • 具有该值的所有节点的深度列表。
  • 错误代码,表明您的查询毫无意义。

任何在特定情况下都有意义。


当然,如果n是指向节点的实际指针,则根本不应该比较节点的值,您应该比较指针。这样,您将只能找到一个匹配,并且它的深度是有意义的。

以下伪代码应该执行以下操作:

def getDepth (Node needle, Node haystack, int value):
    // Gone beyond leaf, it's not in tree

    if haystack == NULL: return -1

    // Pointers equal, you've found it.

    if needle == haystack: return value

    // Data not equal search either left or right subtree.

    if needle.data < haystack.data:
        return getDepth (needle, haystack.left, value + 1)

    if needle.data > haystack.data:
        return getDepth (needle, haystack.right, value + 1)

    // Data equal, need to search BOTH subtrees.

    tryDepth = getDepth (needle, haystack.left, value + 1)
    if trydepth == -1:
        tryDepth = getDepth (needle, haystack.right, value + 1)

    return trydepth

当值相等时,您必须搜索两个子树的原因是因为所需节点可能位于任一子树中。在值不相等的情况下,您知道它在哪个子树中。因此,对于它们相等的情况,您检查一个子树,如果没有找到,则检查另一个子树。

答案 1 :(得分:0)

在您显示的代码中,无法选择具有相同值的一个节点而不是另一个节点。你需要有一些区分标准。 您可以使用以下方法检索所有重复节点深度的列表,例如:

  1. 查找节点的深度。
  2. 查找从找到的节点出现的左子树的同一节点的深度 - 如果未找到则停止。
  3. 将先前找到的节点(在1中)的深度添加到重复的深度
  4. 查找从找到的节点出现的右子树的相同节点的深度(在1中) - 如果找不到则停止。
  5. 将先前找到的节点(在1中)的深度添加到重复的深度
  6. 重复左右子树。
  7. 另见:What's the case for duplications in BST?

相关问题