Leetcode 1382: Balance a Binary Search Tree

grid47
grid47
Exploring patterns and algorithms
Jun 21, 2024 6 min read

Given the root of a binary search tree (BST), return a balanced BST containing the same node values. A balanced BST is one where the depth of the left and right subtrees of every node never differ by more than 1.
Problem
Approach
Steps
Complexity
Input: The input is a binary search tree (BST) represented as an array where each element is a node of the tree.
Example: Input: root = [1, null, 2, null, 3, null, 4]
Constraints:
• The number of nodes in the tree is between 1 and 10,000.
• The value of each node is between 1 and 100,000.
Output: The output is a balanced binary search tree (BST) containing the same node values from the input tree. The tree should be balanced in such a way that the difference in height between the left and right subtrees of any node is at most 1.
Example: Output: [2, 1, 3, null, null, null, 4]
Constraints:
• The tree must be balanced according to the problem definition.
Goal: The goal is to return a balanced BST that contains the same node values as the input BST.
Steps:
• 1. Perform an inorder traversal on the BST to get the nodes in sorted order.
• 2. Use the sorted nodes to construct a balanced BST by recursively selecting the middle node as the root and dividing the remaining nodes into left and right subtrees.
Goal: The solution must be efficient enough to handle up to 10,000 nodes.
Steps:
• The solution must be able to handle a large number of nodes (up to 10,000).
• The value of each node is within the range of 1 to 100,000.
Assumptions:
• The input tree is a binary search tree (BST).
• A balanced BST is defined as a tree where the height difference between the left and right subtrees of every node is at most 1.
Input: Input: root = [1, null, 2, null, 3, null, 4]
Explanation: The input tree is right-skewed. To balance it, we first extract the nodes in sorted order: [1, 2, 3, 4]. We then construct a new tree with the middle element (2) as the root, and recursively build left and right subtrees from the remaining nodes.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus