Find min and max value in a BST

Pattern: Search, insert and delete

medium

The smallest value is at the far left of a BST and the largest at the far right. Walk left from the root until there is no left child, and right until there is no right child.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return [smallest, largest] value of a non-empty BST. [4, 2, 7, 1, 3] gives [1, 7]. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Where can a value smaller than the root be?
  • When do you stop going left?
  • Is the smallest value always a leaf?

Hints

    Brute force, and why it fails

    Visit every node: O(n).

    The key insight

    The BST order puts the extremes at the ends of the left and right spines.

    Dry run

    min1

    BST [4, 2, 7, 1, 3]. Left from 4: 2, then 1, which has no left child.

    Step 1 of 3

    The plan

    lo = root; while lo.left: lo = lo.left
    hi = root; while hi.right: hi = hi.right
    

    Complexity

    Time
    O(h)
    Space
    O(1)

    Two paths down.

    Edge cases

    • One node: [v, v].
    • No left subtree: the root is the minimum.
    • A chain.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] minMax(TreeNode root) {
            TreeNode lo = root, hi = root;
            while (lo.left != null) lo = lo.left;    // the far left is the smallest
            while (hi.right != null) hi = hi.right;  // the far right is the largest
            return new int[]{lo.val, hi.val};
        }
    }

    C++

    class Solution {
    public:
        vector<int> minMax(TreeNode* root) {
            TreeNode* lo = root;
            TreeNode* hi = root;
            while (lo->left != NULL) lo = lo->left;     // the far left is the smallest
            while (hi->right != NULL) hi = hi->right;   // the far right is the largest
            return vector<int>{lo->val, hi->val};
        }
    };

    Python

    class Solution:
        def minMax(self, root) -> list[int]:
            lo = hi = root
            while lo.left:
                lo = lo.left                        # the far left is the smallest
            while hi.right:
                hi = hi.right                       # the far right is the largest
            return [lo.val, hi.val]

    Common mistakes

    • Stopping at the first leaf found.
    • Searching both subtrees.

    Similar problems