Search in BST

Binary Search Trees Theory and Basics Easy

Given the root of a binary search tree (BST) and an integer val.

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

Examples:

Input : root = [4, 2, 7, 1, 3] , val = 2

Output : [2, 1, 3]

Explanation :

Input : root = [4, 2, 7, 1, 3] , val = 5

Output : []

Explanation :

Input : root = [10, 2, 12, 1, 4, null, null, null, null, 3] , val = 2

Constraints

  • 1 <= Number of Nodes <= 5000
  • 1 <= Node.val <= 107
  • 1 <= val <= 107
  • All nodes values in BST are unique.

Hints

  • If val == root.val, return the subtree rooted at this node. If val < root.val, recursively search in the left subtree. If val > root.val, recursively search in the right subtree.
  • If val matches the current node, return it. If val < root.val, move to the left subtree. If val > root.val, move to the right subtree. If null is reached, return null (value not found).

Company Tags

Visa Bain & Company Salesforce GE Healthcare Byju's Alibaba Lyft eBay Databricks Siemens Healthineers Splunk IBM Mastercard Etsy Roblox Epic Games PayPal PwC Docker Zomato Dropbox Twilio Johnson & Johnson AMD OYO Rooms Google Microsoft Amazon Meta Apple Netflix Adobe