oneby7

Binary Search Trees BST basics

383. Minimum and Maximum in a BST

Easy

You are given root, the root node of a binary search tree. Return the smallest and the largest value in the tree, as a list of two values: [minimum, maximum].

In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. The values in the tree are distinct.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

202530405060708090

Input: root = [50, 30, 80, 20, 40, 70, 90, null, 25, null, null, 60]

Output: [20,90]

Explanation: From smallest to largest, the values are 20, 25, 30, 40, 50, 60, 70, 80, 90. The smallest is 20 and the largest is 90.

Example 2

-7

Input: root = [-7]

Output: [-7,-7]

Explanation: The tree has one node, so its value is both the smallest and the largest.

Example 3

-40-25-10-5

Input: root = [-40, null, -10, -25, -5]

Output: [-40,-5]

Explanation: Every value is negative. The root, −40, has no left subtree, so no value is smaller than it. The largest value is −5.

Check your understanding

Work out the answer for this input before you write any code.

root = [40, 20, 60, 10, 30, 50, 70, 5]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • The tree is a binary search tree, and its values are distinct.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.