繁体   English   中英

java中二叉树的一种方法

[英]A method for Binary Tree in java

fill() 方法是填充高度级别内的所有 null TreeNodes。 但是当我运行这段代码时,它会抛出 NullPointerException,我不知道这里发生了什么。

public void fill() {
    int height = height(overallRoot);
    overallRoot = fill(overallRoot, height);
}

//Fill all of the nodes within the height level
private IntTreeNode fill(IntTreeNode root, int height) {
    if (height == 0) { //if reaches the max height, don't add any node
        return null;
    } else if (root == null) { //if do not reach max height and root is null, add a series   
                               //of new nodes until it reaches the max height
        return new IntTreeNode(0, fill(root.left, height - 1), fill(root.right, height - 1));
    } else { 
        root.left = fill(root.left, height - 1);
        root.right = fill(root.right, height - 1);
    }
    return root;
} 

//returns the height of a tree
private int height(IntTreeNode root) {
    if (root == null) {
        return 0;
    } else {
        return 1 + Math.max(height(root.left), height(root.right));
    }
}

看看你的第一个else if 您首先确定(root == null) ,然后尝试检查它的leftright ,尽管已经知道它是null因此没有leftright

暂无
暂无

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

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