1382. Balance a Binary Search Tree #269
-
Topics: Given the A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem requires us to return a balanced binary search tree (BST) given the root of an unbalanced BST. The tree should maintain the same node values as the original tree but be structured in such a way that it is balanced. A balanced binary tree is one in which the depth of the two subtrees of every node differs by no more than 1. Key Points
Approach
Plan
Let's implement this solution in PHP: 1382. Balance a Binary Search Tree <?php
/**
* @param TreeNode $root
* @return TreeNode
*/
function balanceBST($root) {
$nums = [];
inorder($root, $nums);
return build($nums, 0, count($nums) - 1);
}
/**
* @param $root
* @param $nums
* @return void
*/
function inorder($root, &$nums) {
if ($root == null)
return;
inorder($root->left, $nums);
$nums[] = $root->val;
inorder($root->right, $nums);
}
/**
* @param $nums
* @param $l
* @param $r
* @return TreeNode|null
*/
function build($nums, $l, $r) {
if ($l > $r)
return null;
$m = (int)(($l + $r) / 2);
return new TreeNode($nums[$m], build($nums, $l, $m - 1), build($nums, $m + 1, $r));
}
// Example usage:
$root1 = [1,null,2,null,3,null,4,null,null];
$root2 = [2,1,3];
echo balanceBST($root1) . "\n"; // Output: [2,1,3,null,null,null,4]
echo balanceBST($root2) . "\n"; // Output: [2,1,3]
?> Explanation:Let's break down the solution into steps:
Example WalkthroughConsider the input tree:
Time Complexity
Thus, the overall time complexity is O(n). Output for ExampleFor the input tree:
The output balanced tree could be:
Or alternatively:
To balance a binary search tree, we use the following steps:
The solution ensures the tree is balanced while maintaining the properties of the original BST. |
Beta Was this translation helpful? Give feedback.
The problem requires us to return a balanced binary search tree (BST) given the root of an unbalanced BST. The tree should maintain the same node values as the original tree but be structured in such a way that it is balanced. A balanced binary tree is one in which the depth of the two subtrees of every node differs by no more than 1.
Key Points