Convert a normal BST into a Balanced BST

Pattern: Search, insert and delete

medium

Read the nodes in sorted order with an inorder walk, then rebuild: the middle node becomes the root, the left half becomes the left subtree and the right half the right subtree, recursively. The result has the smallest possible height.

The problem

Return a height-balanced BST with the same values (at every node the two subtree heights differ by at most 1). Several trees are correct, so the tests print the inorder and check that the result is a BST and balanced. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • How do you get the values in sorted order?
  • Which value should be the root to balance the sizes?
  • What happens to each half?

Hints

    Brute force, and why it fails

    Rotate nodes one at a time (like an AVL tree): far more code.

    The key insight

    Choosing the middle of a sorted list as the root splits the rest evenly, so the depth is about log n.

    Dry run

    10 
    21 
    32 
    43 

    BST [1, null, 2, null, 3, null, 4]: a chain. Sorted nodes 1, 2, 3, 4.

    Step 1 of 3

    The plan

    nodes = inorder(root)
    build(lo, hi): if lo > hi: null; mid = (lo + hi) / 2; node = nodes[mid]
      node.left = build(lo, mid - 1); node.right = build(mid + 1, hi)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One walk and one rebuild; the list holds every node.

    Edge cases

    • Already balanced.
    • One node.
    • A long chain.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public TreeNode balanceBST(TreeNode root) {
            List<TreeNode> nodes = new ArrayList<>();
            collect(root, nodes);                    // the nodes in sorted order
            return build(nodes, 0, nodes.size() - 1);
        }
    
        private void collect(TreeNode n, List<TreeNode> out) {
            if (n == null) return;
            collect(n.left, out);
            out.add(n);
            collect(n.right, out);
        }
    
        private TreeNode build(List<TreeNode> nodes, int lo, int hi) {   // the middle becomes the root
            if (lo > hi) return null;
            int mid = (lo + hi) / 2;
            TreeNode root = nodes.get(mid);
            root.left = build(nodes, lo, mid - 1);
            root.right = build(nodes, mid + 1, hi);
            return root;
        }
    }

    C++

    class Solution {
    public:
        TreeNode* balanceBST(TreeNode* root) {
            vector<TreeNode*> nodes;
            collect(root, nodes);                    // the nodes in sorted order
            return build(nodes, 0, static_cast<int>(nodes.size()) - 1);
        }
    
        void collect(TreeNode* n, vector<TreeNode*>& out) {
            if (n == NULL) return;
            collect(n->left, out);
            out.push_back(n);
            collect(n->right, out);
        }
    
        TreeNode* build(vector<TreeNode*>& nodes, int lo, int hi) {   // the middle becomes the root
            if (lo > hi) return NULL;
            int mid = (lo + hi) / 2;
            TreeNode* root = nodes[mid];
            root->left = build(nodes, lo, mid - 1);
            root->right = build(nodes, mid + 1, hi);
            return root;
        }
    };

    Python

    class Solution:
        def balanceBST(self, root):
            nodes = []
    
            def collect(n):                         # the nodes in sorted order
                if n:
                    collect(n.left)
                    nodes.append(n)
                    collect(n.right)
    
            def build(lo, hi):                      # the middle becomes the root
                if lo > hi:
                    return None
                mid = (lo + hi) // 2
                root = nodes[mid]
                root.left, root.right = build(lo, mid - 1), build(mid + 1, hi)
                return root
    
            collect(root)
            return build(0, len(nodes) - 1)

    Common mistakes

    • Building from the original order instead of the sorted one.
    • Choosing the first element as the root.

    Similar problems