oneby7

Binary Search Trees BST basics

382. Search in a Binary Search Tree

Easy

You are given root, the root node of a binary search tree, and an integer val. Find the node that holds val and return it. The node brings everything below it, so the answer is the subtree rooted at that node. If no node holds val, return null.

In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. The values in the tree are distinct.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out. The output shows the subtree you return the same way, and null as [].

Example 1

81723293541607395
root
232935
output

Input: root = [41, 17, 73, 8, 29, 60, 95, null, null, 23, 35] val = 29

Output: [29,23,35]

Explanation: The node 29 is the right child of 17. Its subtree holds 29 and its two children, 23 and 35.

Example 2

136810

Input: root = [8, 3, 10, 1, 6], val = 7

Output: []

Explanation: No node holds 7, so the answer is null.

Example 3

−10⁹010⁹
root
−10⁹010⁹
output

Input: root = [0, -1000000000, 1000000000], val = 0

Output: [0,-1000000000,1000000000]

Explanation: The root holds 0, so the answer is the whole tree.

Check your understanding

Work out the answer for this input before you write any code.

root = [30, 12, 45, 6, 18, 40, 52], val = 45

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • The tree is a binary search tree, and its values are distinct.
  • -109 ≤ val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.