如何找到一个二叉搜索树的高度

sgtfey8w  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(285)

我有一个由字符串组成的binarysearchtree,我有我的方法来查找高度、插入等。但是我很难在主类中实现它,因为我的findheight方法需要一个节点,我试图在其中传递一个字符串。你能帮我大体上如何实施吗?我的减肥法

int findHeight(TreeNode aNode) {
        if (aNode == null) {
            return -1;
        }

        int lefth = findHeight(aNode.left);
        int righth = findHeight(aNode.right);

        if (lefth > righth) {
            return lefth + 1;
        } else {
            return righth + 1;
        }
    }

我的主代码

// I got a BinarySearchTree object as bst
        bst.findHeight(root);
        //it gives me -1 with that

我应该怎么用(我将给定数组中的所有元素插入到tree)insert方法中

public void insert(String d) {
        if (root == null) { // must handle case of empty tree first
            root = new TreeNode(d);
            return;
        }
        TreeNode loc = root; // start search downward at root
        while (true) {
            if (d.compareTo(loc.data) < 0) { // look left
                if (loc.left != null)
                    loc = loc.left;
                else {
                    loc.left = new TreeNode(d);
                    break;
                }
            } else if (d.compareTo(loc.data) > 0) { // look right
                if (loc.right != null)
                    loc = loc.right;
                else {
                    loc.right = new TreeNode(d);
                    break;
                }
            } else
                break; // found! Don't insert
        }
    }

主要类别

for (int i = 0; i < aArr.length; i++) {
            bst.insert(aArr[i]);

        }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题