java - 在树中查找值
问题描述
我需要创建一个方法来检查给定的整数是否存在于树中,并分别返回真或假。这棵树不是二叉搜索树,因此左侧节点的值并不总是更小。我的构造函数如下:
public class TreeNode {
TreeNode left;
int payload;
TreeNode right;
public TreeNode(int x){
payload = x;
}
以下方法完美运行:
public boolean find(int x,TreeNode root) {
if (root.payload == x) {
return true;
} if (root.left != null && find(x, root.left)){
return true;
}if (root.right != null && find(x, root.right)) {
return true;
}
return false;
}
但是我意识到我需要按照指南进行操作,如下所示:
public Boolean find(int x)
如何更改我的代码以实现此版本?
解决方案
通过将传递树来调用方法替换为实例方法this
:
public Boolean find(int x) {
if (this.payload == x) {
return true;
} if (this.left != null && this.left.find(x)){
return true;
}if (this.right != null && this.right.find(x)) {
return true;
}
return false;
}
推荐阅读
- docker - Aspose Word v18.8.0 中的“SkiaSharp.SKImageInfo”异常
- c# - Unity:在时间轴 [VR/3D] 中激活时,相机重置为零位置
- gulp - 子进程使用 gulp-run 执行命令任务时发生错误
- reactjs - 如何解决反应js中的“useRef不是函数错误”
- pouchdb - PouchDb 与 CouchDb 不同步......为什么复制不能修复它?
- tfs - VSTS下无法添加新分支
- python - 当应用 word2vec 时,只显示字符而不是单词 ؟
- mips - 如何确定整数的 ASCII 表示是负数还是正数
- c# - “在哪里”和“选择”如何在 LINQ 中工作?
- c - 如果语句在 C KDMF 驱动程序中失败