Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1382: Balance a Binary Search Tree

In this guide, we solve Leetcode #1382 Balance a Binary Search Tree in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Greedy, Tree, Depth-First Search, Binary Search Tree, Divide and Conquer, Binary Tree

Intuition

A locally optimal choice leads to a globally optimal result for this structure.

That means we can commit to decisions as we scan without backtracking.

Approach

Sort or preprocess if needed, then repeatedly take the best available local choice.

Maintain the minimal state necessary to validate the greedy decision.

Steps:

  • Sort or preprocess as needed.
  • Iterate and pick the best local option.
  • Track the current solution.

Example

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.

Python Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: def dfs(root: TreeNode): if root is None: return dfs(root.left) nums.append(root.val) dfs(root.right) def build(i: int, j: int) -> TreeNode: if i > j: return None mid = (i + j) >> 1 left = build(i, mid - 1) right = build(mid + 1, j) return TreeNode(nums[mid], left, right) nums = [] dfs(root) return build(0, len(nums) - 1)

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy