Advertisement
amitsen01ei

BSTSearch.java

Sep 24th, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | Source Code | 0 0
  1. public class BSTSearch {
  2.  
  3.     /**
  4.      *Finds the given value in the binary search tree. The TreeNode class is assumed as below:
  5.      * <pre>{@code
  6.      * public class TreeNode {
  7.      *
  8.      *     int val;
  9.      *
  10.      *     TreeNode left;
  11.      *
  12.      *     TreeNode right;
  13.      * }
  14.      * }</pre>
  15.      * <p>
  16.      *     <b>Time Complexity:</b>
  17.      *     The search in a balanced BST takes <b>O(log n)</b> time. However,
  18.      *     in the worst-case scenario (i.e., the tree is a skewed tree),
  19.      *     the time complexity can go up to <b>O(n)</b>.
  20.      * </p>
  21.      * <p>
  22.      *     <b>Space Complexity:</b>
  23.      *     The space complexity is <b>O(h)</b>, where h is the height of the tree.
  24.      *     This is because of the call stack size in a recursive approach.
  25.      *     Again, for a balanced BST, this will be <b>O(log n)</b>, but for a skewed tree,
  26.      *     it could go up to <b>O(n)</b>.
  27.      * </p>
  28.      * @param root node of the BST
  29.      * @param val to search
  30.      * @return subtree rooted with the val
  31.      *         <p>null if not found</p>
  32.      */
  33.  
  34.     public TreeNode searchBST(TreeNode root, int val) {
  35.         if (root == null) return null;
  36.         if (root.val == val) return root;
  37.  
  38.         if (root.val < val) {
  39.             return searchBST(root.right, val);
  40.         }
  41.  
  42.         return searchBST(root.left, val);
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement