TRT
Sign in
mediumAdvancedLeetCode#in-order traversal#rebuild from sorted keys

Balance a binary search tree

Turn any binary search tree into a balanced one with the same keys, by flattening it in order and rebuilding.

The Runtime Theory Team1 min read
Taught inAVL rotationsPro — members onlyAn AVL tree keeps the heights of every node's two subtrees within one of each other. After an insert, at most one or two rotations, local pointer rearrangements that preserve key order, restore that rule and keep the height below 1.44 log₂ n.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [1, null, 2, null, 3, null, 4]

outa balanced BST such as [2, 1, 3, null, null, null, 4]

inroot = [2, 1, 3]

out[2, 1, 3]

inroot = [5, 4, null, 3, null, 2, null, 1]

outa balanced BST such as [3, 1, 4, null, 2, null, 5]

Given the root of a binary search tree, return a balanced binary search tree with the same values, where the depths of every node's two subtrees differ by at most one. Any valid answer is accepted.

Before you code

The input may be a chain. Which traversal produces the keys in sorted order, and what do you do with sorted keys?

Hints

  1. Collect the values with an in-order traversal, iteratively if the tree may be deep. They come out sorted.
  2. Rebuild with the middle value as the root, recursively, in O(n).
  3. Compare with inserting the values one by one into an AVL tree, with rotations: O(n log n), but it keeps working as new keys arrive.

Production & complexity notes

When solving Balance a binary search tree on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in AVL rotations to reinforce the underlying pattern.

What it practices

The balance invariant, and the two ways of restoring it, from AVL rotations.

Not started

Sign in to save your learning progress.

Sign in to save