Earn extra honor and gain new allies!
Honor is earned for each new codewarrior who joins.
Learn more
Search
Algorithms

Recursive traversal is prettier :-P

Code
Diff
  • import java.util.*;
    
    class Node {
      int value;
      Node left;
      Node right;
      
      public Node(int value) {
        this.value = value;
      }
    }
    
    
    class BST {
      public static boolean search(Node root, int key) {   
          if (root == null){
              return false;
          }else if(root.value == key) {
            return true;
          } else{
              return root.value > key ? search(root.left, key) : search(root.right, key); 
          }
      }
    }
  • 1010 }
    1111 }
    1212
    1313
    1414 class BST {
    1515 public static boolean search(Node root, int key) {
    16- while(root != null) {
    17- if(root.value == key) {
    16+ if (root == null){
    17+ return false;
    18+ }else if(root.value == key) {
    1818 return true;
    20+ } else{
    21+ return root.value > key ? search(root.left, key) : search(root.right, key);
    1919 }
    20-
    21- if(root.value > key) {
    22- root = root.left;
    23- } else if(root.value < key) {
    24- root = root.right;
    25- }
    26- }
    27-
    28- return false;
    2929 }
    3030 }