#1382

Balance a Binary Search Tree

pupil · 380 · lc medium +24 · verified · 86.3% accepted · 4,162 likes · top 97%

Description

Given the root of a binary search tree, reconstruct it as a height-balanced BST containing the same node values. A BST is balanced when no node's two subtrees differ in depth by more than 1. Return any valid result.

Example 1:

Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.

Example 2:

Input: root = [2,1,3]
Output: [2,1,3]

Code

1
2
3
4
5
6
7
8
9