Ad
Search
Algorithms
Logic

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); 
          }
      }
    }
    • 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) {
    • while(root != null) {
    • if(root.value == 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);
    • }
    • if(root.value > key) {
    • root = root.left;
    • } else if(root.value < key) {
    • root = root.right;
    • }
    • }
    • return false;
    • }
    • }