Saturday, March 21, 2015

Implement BST Search

Search in a binary search tree.

Solution1: iterative
Run time complexity is O(logn), constant space.
//iterative
 public static boolean search(TreeNode root, int num) {
     if(root == null) {
         return false;
     }
  
     TreeNode node = root;
     while(node.val != num) {
         if(node.val < num) {
             node = node.right;
         }else {
             node = node.left;
         }
         if(node == null) {
             return false;
         }
     }
     return true;
 }

Solution2: recursion
Run time complexity is O(logn), stack space.
//recursion
 public static boolean searchRec(TreeNode root, int num) {
     if(root == null)
         return false;
  
     if(root.val == num)
         return true;
  
     if(root.val < num) {
         return searchRec(root.right, num);
     }else {
         return searchRec(root.left, num);
     }
 }

No comments:

Post a Comment