简体   繁体   中英

Search operation in Binary search tree

在二叉搜索树(递归或循环)中哪个更好地实现搜索操作?

There is no need for recursion in case you want to search . Recursion would be an overkill for this situation . Just write a loop and break when found or break at leaf node (if not found)

I usually find recursion easier to implement and, at least with trees, makes your code more readable for other human beings. But at the end it depends on whether your tree is balanced or not

  • If your tree is balanced then I think you can surely use recursion since you are guaranteed that the recursive calls will not exceed log(n) ( Eg for n=100000000 the worst number of recursive calls you will have to make are only around 27)

  • If on the other hand your tree is not balanced then I think looping is your best bet since you might have to check all the elements of the tree and recursion will use a huge amount of memory for maintaining the stack.

While(current != null) works.

public class BST<E extends Comparable<E>> 
  extends AbstractTree<E> {

  protected TreeNode<E> root;

  protected int size = 0;

~ ~ ~ ~

// Returns true if the element is in the tree 
  public boolean search(E e) {
    TreeNode<E> current = root; // Start from the root

    while (current != null) {
      if (e.compareTo(current.element) < 0) {
        current = current.left;
      }
      else if (e.compareTo(current.element) > 0) {
        current = current.right;
      }
      else // element matches current.element
        return true; // Element is found
    }

    return false;
  }

Assuming you have an entity class BinaryTreeNode, here is the non-recursive implementation of searching a node in Binary Search Tree:

public static BinaryTreeNode searchBstNode(BinaryTreeNode temp, int data){

    while(true){
        if(temp.getData()==data){
            break;
        }
        if(temp.getData()>data){
            if(temp.getLeft()!=null){
                temp=temp.getLeft();    
            }
            else{
                System.out.println("Data value ="+ data+" not found!");
                return null;
            }   
        }
        if(temp.getData()<data){
            if(temp.getRight()!=null){
                temp=temp.getRight();
            }
            else{
                System.out.println("Data value ="+ data+" not found!");
                return null;
            }

        }
    }
    System.out.println("Data found in the BST");
    return temp;

What is best algorithms will be depend on the context of the problem we arr going to solve.This wiki page shows good com prison between these two. Hope this will helpful. http://en.wikipedia.org/wiki/Binary_search_algorithm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM