Locate a Subtree by Its Search Key

Quick Overview

Locate a Subtree by Its Search Key. Given the root pointer of a binary search tree and val, return the existing node whose value equals val, including its entire subtree.

Locate a Subtree by Its Search Key

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Given the root pointer of a binary search tree and val, return the existing node whose value equals val, including its entire subtree. Return nullptr when no matching node exists. TreeNode is the original node type; level-order lists below only describe trees. ```cpp class Solution { public: TreeNode* searchBST(TreeNode* root, int val); }; ``` ### Examples **Example 1:** ```text root = [8,4,11,2,6], val = 4 Output subtree: [4,2,6] Explanation: Return the original node holding 4. ``` **Example 2:** ```text root = [8,4,11,2,6], val = 7 Output: nullptr Explanation: No node has value 7. ``` ### Constraints - The BST contains 1 through 5000 nodes. - Both node values and val are in [1,10000000]. - The given tree satisfies the binary-search ordering. ### Contract considerations Preserve the TreeNode pointer input and subtree result. ```hint Read the boundary condition Which subtree can still contain the desired key? ``` ### Boundary reminders Preserve the TreeNode pointer input and subtree result.

Overview: Locate a Subtree by Its Search Key. Given the root pointer of a binary search tree and val, return the existing node whose value equals val, including its entire subtree.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Given the root pointer of a binary search tree and val, return the existing node whose value equals val, including its entire subtree. Return nullptr when no matching node exists. TreeNode is the original node type; level-order lists below only describe trees.

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val);
};

Examples

Example 1:

root = [8,4,11,2,6], val = 4
Output subtree: [4,2,6]
Explanation: Return the original node holding 4.

Example 2:

root = [8,4,11,2,6], val = 7
Output: nullptr
Explanation: No node has value 7.

Constraints

  • The BST contains 1 through 5000 nodes.
  • Both node values and val are in [1,10000000].
  • The given tree satisfies the binary-search ordering.

Contract considerations

Preserve the TreeNode pointer input and subtree result.

Boundary reminders

Preserve the TreeNode pointer input and subtree result.