LeetCode 1382: Balance a Binary Search Tree Solution

Master LeetCode problem 1382 (Balance a Binary Search Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To balance a binary search tree, we can perform an in-order traversal of the original BST to collect all the nodes into a sorted array. Then, we can recursively build a balanced BST from the sorted array by selecting the middle element as the root and recursively constructing the left and right subtrees. This approach ensures the balanced property of the resulting binary search tree.

Algorithm:

  1. Perform an in-order traversal of the original BST to collect all nodes into a sorted array.
  2. Recursively build a balanced BST from the sorted array:
    • Select the middle element as the root.
    • Recursively build the left subtree from the elements to the left of the middle.
    • Recursively build the right subtree from the elements to the right of the middle.

Time Complexity: O(n) where n is the number of nodes in the tree.

Space Complexity: O(n) for storing the nodes in the sorted array.

Solution Code

class Solution {
    public TreeNode balanceBST(TreeNode root) {
        List<TreeNode> nodes = new ArrayList<>();
        inOrderTraversal(root, nodes);
        return buildBalancedBST(nodes, 0, nodes.size() - 1);
    }
    
    private void inOrderTraversal(TreeNode node, List<TreeNode> nodes) {
        if (node == null) return;
        inOrderTraversal(node.left, nodes);
        nodes.add(node);
        inOrderTraversal(node.right, nodes);
    }
    
    private TreeNode buildBalancedBST(List<TreeNode> nodes, int start, int end) {
        if (start > end) return null;
        
        int mid = start + (end - start) / 2;
        TreeNode root = nodes.get(mid);
        
        root.left = buildBalancedBST(nodes, start, mid - 1);
        root.right = buildBalancedBST(nodes, mid + 1, end);
        
        return root;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1382 (Balance a Binary Search Tree)?

This page provides optimized solutions for LeetCode problem 1382 (Balance a Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1382 (Balance a Binary Search Tree)?

The time complexity for LeetCode 1382 (Balance a Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1382 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1382 in Java, C++, or Python.

Back to LeetCode Solutions