首页 > 解决方案 > 在树中查找值

问题描述

我需要创建一个方法来检查给定的整数是否存在于树中,并分别返回真或假。这棵树不是二叉搜索树,因此左侧节点的值并不总是更小。我的构造函数如下:

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)

如何更改我的代码以实现此版本?

标签: javaoopif-statementrecursiondata-structures

解决方案


通过将传递树来调用方法替换为实例方法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;

}

推荐阅读