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)
,然后尝试检查left
and right
,尽管已经知道它是null
并且因此没有 aleft
或 a right
。
推荐阅读
- r - 在 Ubuntu 18.04.5 LTS 中启动 Docker 服务失败
- javascript - 函数 A 调用函数 B,而函数 B 调用函数 A:ESLint 给出错误:在定义之前使用了“函数 B”
- xamarin.forms - 在具有大量 nuget 引用的大型 Xamarin.Forms 项目中,我在执行 UWP 的 .NET Native 版本构建时遇到 rhbind RHB0002 错误
- javascript - NestJS/TS 中的依赖地狱
- nlp - 如何在文本分类中显示随机森林的特征重要性?
- c# - 想在一种方法中插入两个表 ASP.NET web api 2
- .net - EFCore - 将复杂属性字段非规范化为父表
- sed - 使用递归 grep 过滤文件,然后对它们内联使用 sed
- python - 已部署的烧瓶服务器站点 - 响应错误的时间过长
- angular - 查看子项不适用于 Modal -Angular 内的 Element Ref