Java 在树中查找值
我需要创建一个方法来检查树中是否存在给定的整数,并分别返回true或false。 该树不是二叉搜索树,因此左侧节点的值并不总是较小。 我的构造函数如下所示:Java 在树中查找值,java,oop,if-statement,recursion,data-structures,Java,Oop,If Statement,Recursion,Data Structures,我需要创建一个方法来检查树中是否存在给定的整数,并分别返回true或false。 该树不是二叉搜索树,因此左侧节点的值并不总是较小。 我的构造函数如下所示: public class TreeNode { TreeNode left; int payload; TreeNode right; public TreeNode(int x){ payload = x; } 以下方法非常有效: public boolean find(in
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;
}
它给出了一个错误:remove-argument-to-match-find(int)