Search for an element in the binary tree java

Ideas

For a given binary tree, if the data value of a node in the tree is found to be the same, it will return true, recursively go down from the root node of the tree, and compare the values ​​of the left and right subtrees to implement the algorithm

boolean FindBinaryTreeUsingRecursion(BinaryTreeNode root,int data){
    
    
  boolean temp;
  //基本情况,空树返回false
  if(root -- null)
    return false;
  else{
    
    
    if(data == root.getData()){
    
    
      return ture;
    }else{
    
    
      //从子树继续递归向下搜索
      temp = FindBinaryTreeUsingRecursion(root.getLeft(),data);
      if(temp == true)
        return temp;
      else
        return FindBinaryTreeUsingRecursion(root.getRight(),data);
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/109956988