EasyTreeBinary Search TreeBinary Tree

Search in a Binary Search Tree

LeetCode
1 approach, code in all languages

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

Locate the node whose value equals val and return the subtree rooted at that node (that is, the node itself along with everything beneath it). If no node in the tree has the value val, return null.

Example 1

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

Output: [2,1,3]

The node with value 2 has children 1 and 3, so the returned subtree is [2,1,3].

Example 2

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

Output: []

No node holds the value 5, so the search returns null (shown as an empty tree).

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now