Search in a Binary Search Tree — LeetCode 700 Python Solution
- Problem
- #700
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
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
# 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.