Search in a Binary Search Tree — LeetCode 700 Python Solution

EasyTreeBinary Search TreeBinary Tree
Problem
#700
Reading time
3 min

The problem

You are 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.

Example

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

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root is None or root.val == val:
            return root
        return (
            self.searchBST(root.left, val)
            if root.val > val
            else self.searchBST(root.right, val)
        )

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 700. Search in a Binary Search Tree is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Tree, Binary Tree and Binary Search Tree.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 700. Search in a Binary Search Tree?
LeetCode 700. Search in a Binary Search Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 700. Search in a Binary Search Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 700. Search in a Binary Search Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 700. Search in a Binary Search Tree cover?
LeetCode 700. Search in a Binary Search Tree is tagged Tree, Binary Search Tree and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview