oneby7

Binary Search Trees BST basics

386. Convert Sorted Array to Binary Search Tree

Easy

You are given an integer array nums, sorted in strictly increasing order. Build a height-balanced binary search tree that holds every value of nums exactly once, and nothing else. Return its root.

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 height of a subtree is the number of nodes on the longest path from its top node down to a leaf, and an empty subtree has height 0. A tree is height-balanced when, at every node, the heights of the left and right subtrees differ by at most 1.

Many trees follow these rules, and any of them is a correct answer. The result shows a height-balanced BST of the given values when your tree is one. Otherwise it names the first thing wrong, such as the tree has 4 nodes, not 5, not a BST of the given values: inorder position 1 holds 7, not 3 or node with value 3 is unbalanced: left height 0, right height 2. The inorder lists a tree's values left subtree first, then the node, then the right subtree, and its positions count from 0.

Each example shows one right tree, written level by level, from left to right, with null where a child is missing. So [5,3,null,1] is the root 5 with a left child 3 and no right child, and 3 has a left child 1. The missing children after the last node are left out.

Example 1

-10-4271330

Input: nums = [-10, -4, 2, 7, 13, 30]

Output: [2,-10,13,null,-4,7,30]

Explanation: The root 2 has the two smaller values on its left and the three larger ones on its right, and each side is built the same way. At every node the two heights differ by at most 1. [7,-4,30,-10,2,13] is also correct.

Example 2

42

Input: nums = [42]

Output: [42]

Explanation: One value makes a tree of a single node.

Example 3

−10⁹10⁹

Input: nums = [-1000000000, 1000000000]

Output: [-1000000000,null,1000000000]

Explanation: With two values, either one can be the root, and the other goes below it on its side. [1000000000,-1000000000] is also correct.

Check your understanding

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

nums = [1, 2, 3, 4, 5]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums is sorted in strictly increasing order.

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.