Search in a Binary Search Tree

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST whose value equals val and return the subtree rooted at that node. If such a node does not exist, return null.

Example 1
        4
       / \
      2   7
     / \
    1   3
Inputroot = [4,2,7,1,3], val = 2
Output[2,1,3]
The node with value 2 exists in the BST, so the subtree rooted at that node is returned.
Example 2
        4
       / \
      2   7
     / \
    1   3
Inputroot = [4,2,7,1,3], val = 5
Output[]
No node in the BST has value 5, so no subtree is returned.

Constraints

  • The number of nodes in the tree is in the range [1, 5000].
  • 1 <= Node.val <= 10^7
  • root is a binary search tree.
  • 1 <= val <= 10^7

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate