Java finds an element in a binary search tree

Ideas

The search operation of the binary search tree is simple and effective. Starting from the root node, based on the nature of the binary search tree, move to the left subtree or the right subtree to continue searching. If the data to be searched is consistent with the node data, the current node will be returned. If the data to be searched is less than the root node data, search the left subtree of the current node, otherwise, search the right subtree of the current node. If the data does not exist, return a null pointer

Code

Recursion:

BinarySearchTreeNode find(BinarySearchTreeNode root,int data){
    
    
  if(root == null)
    return null;
  if(data > root.getData()){
    
    
    return find(root.getRight(),data);
  }else if(data < root.getData()){
    
    
    return find(root.getLeft(),data);
  }
  return root;
}

非递归:


```java
BinarySearchTreeNode find(BinaryTreeNode root,int data){
    
    
  if(root == null)
    return null;
  while(root != null){
    
    
    if(root.getData() == data){
    
    
      return root;
    }
    else if(root.getData() > data){
    
    
      root = root.getLeft();
    }
    else{
    
    
      root = root.getRight();
    }
  }
  return null;
}

Guess you like

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