java - 如何在第一层类的方法体内使用嵌套类中的方法
问题描述
我正在学习系统工程只有 2 个月,所以请放轻松。我正在开发一个包含列表、堆栈和二叉树的项目。我遇到问题的代码是二叉树内部的代码。
public class BinaryIntTree {
public static class Node {
int value;
The left child.
Node leftChild;
public int getNodeCount(Node node) {
if(node == null) {return 0;}
int counter = 0;
if(node.leftChild == null && node.rightChild == null) {
return 1;
} else {
counter += 1;
if (node.leftChild != null) {
counter += getNodeCount(node.leftChild);
}
if (node.rightChild != null) {
counter += getNodeCount(node.rightChild);
}
}
return counter;
}
public Node(int value) {
this.value = value;
}
public int getNodeCount() {
return root.getNodeCount(root);
}
第二个 getNodeCount() 在 Main 类中,我希望,如果我使用 getNodeCount(),我无法更改用作起点的 Object(root)。所以我认为 id 只是在嵌套的 Node 类中实现它,并让它在 Main 类的 Method 中调用。
但它抛出了一个 NullPointerException,应该用 if(node == null) {return 0;} 解决它,但它没有。提前感谢您的帮助,也请不要对方法本身发表评论,因为我想自己解决递归方法。
解决方案
getNodeCount
将 aNode
作为参数,并且不使用Node
它被调用的实例(即 the this
),这意味着它可能应该是static
. 一旦你把它变成静态的,你可以在没有实例的情况下调用它,从而避免NullPointerException
你遇到:
public int getNodeCount() {
return Node.getNodeCount(root);
}
推荐阅读
- python - Python DateTime 将日期时间输入列表转换为仅日期格式
- c# - 构建表达式以过滤数据 EF Core
- python - Protobuf-net 无法识别的流前缀
- vue.js - 对过滤后的数组进行排序
- node.js - 如何减少 Sequelize 请求时间?(Ajax 响应耗时太长)
- python - 为什么 SymPy 求解为高阶多项式提供空集?
- javascript - 为什么我可以在 for...of 循环中使用 await 关键字
- google-chrome-extension - 为什么建议在 Chrome 扩展程序的后台页面而不是内容脚本中进行 API 调用?
- aws-lambda - Terraform 在 zip 准备好之前创建 lambda
- c - 在C中打印指向链表的双指针