java - java中二叉树的一种实现方法

标签 java

fill()方法是填充高度范围内所有空的TreeNode。但是当我运行这段代码时,它抛出 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

关于java - java中二叉树的一种实现方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58946459/

相关文章:

java - SSL 握手失败 - HttpClient 4.1.2

java - Spring Boot 响应实体不返回 JSON

java - 我们如何将 JML (openJML) 应用于 Java 代码?

java - jHipster:8080 和 9000 端口上的不同版本

java - java中如何将ArrayList转成String[],Arraylist包含VO对象

java - 如何获取引导类加载器加载的所有类的列表?

java - System.in() 是如何工作的?

java - Remember Me 如何在 Spring Security 中工作?

java - 反序列化 JSON 时,gson 如何将 JSON 键与 Java 类中的字段映射

repl.it 上的 Java java.awt.HeadlessException : No X11 DISPLAY variable was set, 但该程序执行了需要它的操作