↓Skip to main content
  1. LeetCode/

LeetCode 700: Search in a Binary Search Tree

·1 min· ·
LeetCode Easy Tree Binary-Search-Tree Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-31

  • Submissions: Accepted (first try)

Approach
#

BST search (Tree Template 3): larger than the target goes left, smaller goes right, equal is found; reaching None means absent.

My Solution
#

class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        while root and root.val != val:
            root = root.left if val < root.val else root.right
        return root

Complexity
#

Time O(h), space O(1).

Mistakes to Avoid
#

  • Return the node (its whole subtree), not the value.

Interview Explanation
#

From the root I go left when larger and right when smaller, returning on a match or at None. Time O(h), space O(1).

Related

LeetCode 501: Find Mode in Binary Search Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 501 note: a BST’s in-order is sorted, so equal values are contiguous; count the current run during in-order, resetting the answer on a new maximum and appending on a tie
LeetCode 703: Kth Largest Element in a Stream
·1 min
LeetCode Easy Tree Design Binary-Search-Tree Heap-Priority-Queue
LeetCode 703 note: keep a min-heap of size k; its top is the k-th largest
LeetCode 530: Minimum Absolute Difference in BST
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Search-Tree
LeetCode 530 note: a BST’s in-order is ascending, so the minimum difference is between in-order neighbors; remember the previous value and compare
LeetCode 637: Average of Levels in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 637 note: level-order traversal, dividing each level’s sum by its count
LeetCode 671: Second Minimum Node In a Binary Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 671 note: the root is the minimum; the second minimum is the smallest value larger than the root, and only subtrees equal to the root need searching
LeetCode 563: Binary Tree Tilt
·1 min
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 563 note: return subtree sums in post-order; each node’s tilt is the difference of its subtree sums, added to the answer