繁体   English   中英

返回二叉搜索树的高度

[英]Return the height of a binary search tree

我有两个类BSTSet和BSTNode,它们都有一个可以返回高度的height()方法。 我收到一个stackoverflow错误,不确定是什么原因引起的。

BSTSet

public class BSTSet <E extends Comparable<E>> extends AbstractSet <E> {

    // the root of the supporting binary search tree
    private BSTNode<E> root;

    // number of elements in the set
    private int count = 0;

    public boolean isEmpty() {
        return count == 0;
    }

    public int size() {
        return count;
    }


    public int height() {
        if(root == null) return -1;
        else return root.height();
    }
}

BSTNode

public class BSTNode <E extends Comparable<E>> {

    private E value;
    private BSTNode<E> left;
    public BSTNode<E> right;

    public BSTNode(E value) {
       this.value = value;
    }

    public E getValue() {
        return value;
    }

    public BSTNode<E> getLeft() {
        return left;
    }

    public BSTNode<E> getRight() {
        return right;
    }

    public int height() {
        if(left == null && right == null) return 0;
        if(left != null  && right == null) {UI.println("left");return left.height()+ 1; }
        else if(right != null && left == null){UI.println("right");return right.height()+ 1;}
        else{UI.println("both"); return Math.max(right.height(), left.height()) + 1;}
    }
}

如果您想要更多的代码或需要更多的信息,请随时询问。

问题是,你的递归height()方法是调用height()this 这不是算法应该如何工作的原因,而无限递归循环的明显原因就是堆栈溢出。

@xgeorgekx的方法应该给出正确的答案,但我不认为这是最佳方法。 如果树是平衡的,则左右子树的高度是相关的……并且您可能不需要遍历两侧。 如果可以避免,那么height方法可以实现为O(logN)而不是O(N)

我怀疑您的原始方法试图成为O(logN) ...

if(left == null && right == null) return 0;

改成

if(left == null && right == null) return 1;

如果节点没有子节点,则其高度仍为1

然后像这样进行递归调用, else return Max(left.height(), right.tHeight) + 1;

根据定义,节点的高度是其子树的最大高度+ 1

堆栈溢出是由于在同一节点上调用了height()方法造成的:

else if(left != null && right == null || left == null && right != null) return height()+ 1;
else return height()+ 2;

我只是想把它扔进去。如果您要一个节点,那么从0高度开始显然要保持if(left == null && right == null) return 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM