如何编写一个函数来检查给定的二进制搜索树是否包含给定的值?

时间:2019-04-22 17:51:51

标签: java recursion binary-tree

例如,对于以下树:

n1(值:1,左:null,右:null) n2(值:2,左:n1,右:n3) n3(值:3,左:null,右:null) 调用contains(n2,3)应该返回true,因为根为n2的树包含数字3。

我是编程的新手,它试图解决理解编程概念的挑战。这不是作业问题。

我已经在下面编写了代码,但始终返回false。

class Node {
   public int value;
   public Node left, right;

   public Node(int value, Node left, Node right) {
     this.value = value;
     this.left = left;
     this.right = right;
   }
  }

 public class BinaryTree {

   public static boolean contains(Node root, int value){
        if(root == null) return false;
        else
            return
                    contains(root.left, value) ||
                    contains(root.right, value);
    }

  public static void main(String[] args) {

        Node n1 = new Node(1, null, null);
        Node n3 = new Node(3, null, null);
        Node n2 = new Node(2, n1, n3);

        System.out.println(contains(n2,3));
    }
 }

1 个答案:

答案 0 :(得分:2)

您没有检查节点上的值是否与您搜索的值相对应。因此,您基本上总是返回false,因为在某一时刻,根将等于null。为了避免这种情况,您需要一个else if子句,在该子句中检查节点的值和搜索到的值,如果这两个相等,则返回true。

public static boolean contains(Node root, int value){
    if(root == null) return false;
    else if (root.value==value) return true;
    else
        return
                contains(root.left, value) ||contains(root.right, value);
}
相关问题