EasyTreeBinary Search TreeBinary Tree

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Pulling A Branch Out Of A Code Index is our own problem on the technique behind Search in a Binary Search Tree: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free