Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BSTSearch {
- /**
- *Finds the given value in the binary search tree. The TreeNode class is assumed as below:
- * <pre>{@code
- * public class TreeNode {
- *
- * int val;
- *
- * TreeNode left;
- *
- * TreeNode right;
- * }
- * }</pre>
- * <p>
- * <b>Time Complexity:</b>
- * The search in a balanced BST takes <b>O(log n)</b> time. However,
- * in the worst-case scenario (i.e., the tree is a skewed tree),
- * the time complexity can go up to <b>O(n)</b>.
- * </p>
- * <p>
- * <b>Space Complexity:</b>
- * The space complexity is <b>O(h)</b>, where h is the height of the tree.
- * This is because of the call stack size in a recursive approach.
- * Again, for a balanced BST, this will be <b>O(log n)</b>, but for a skewed tree,
- * it could go up to <b>O(n)</b>.
- * </p>
- * @param root node of the BST
- * @param val to search
- * @return subtree rooted with the val
- * <p>null if not found</p>
- */
- public TreeNode searchBST(TreeNode root, int val) {
- if (root == null) return null;
- if (root.val == val) return root;
- if (root.val < val) {
- return searchBST(root.right, val);
- }
- return searchBST(root.left, val);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement