1382. Balance a Binary Search Tree
Medium
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.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
Example 1:
Example 2:
Constraints:
Solution:
/** * Definition for a binary tree node. * class TreeNode { * public $val = null; * public $left = null; * public $right = null; * function __construct($val = 0, $left = null, $right = null) { * $this->val = $val; * $this->left = $left; * $this->right = $right; * } * } */ class Solution { /** * @param TreeNode $root * @return TreeNode */ function balanceBST($root) { $nums = []; $this->inorder($root, $nums); return $this->build($nums, 0, count($nums) - 1); } function inorder($root, &$nums) { if ($root == null) return; $this->inorder($root->left, $nums); $nums[] = $root->val; $this->inorder($root->right, $nums); } function build($nums, $l, $r) { if ($l > $r) return null; $m = (int)(($l + $r) / 2); return new TreeNode($nums[$m], $this->build($nums, $l, $m - 1), $this->build($nums, $m + 1, $r)); } }Contact Links
The above is the detailed content of Balance a Binary Search Tree. For more information, please follow other related articles on the PHP Chinese website!