题意:

image.png

解题思路:

  1. 思路:DFS[O(n),其中 n 是数组的长度,每个数字只访问一次]
  2. 1. 平衡二叉搜索树的特点是左右子树高度差在1内,每个节点左子树小于右子树;
  3. 2. BST的中序遍历是升序的,又因为题中要求是高度平衡二叉搜索树,因此可以选择升序序列中间元素作为根节点;
  4. 3. 根左边元素一定小于根节点,右边元素则大于根节点,递归左右子树构造平衡二叉树;

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param Integer[] $nums
  13. * @return TreeNode
  14. */
  15. function sortedArrayToBST($nums) {
  16. return $this->helper($nums, 0, count($nums) - 1);
  17. }
  18. function helper($nums, $left, $right) {
  19. if ($left > $right) return null;
  20. $mid = $left + floor(($right - $left) >> 1);
  21. $node = new TreeNode($nums[$mid]);
  22. $node->left = $this->helper($nums, $left, $mid - 1);
  23. $node->right = $this->helper($nums, $mid + 1, $right);
  24. return $node;
  25. }
  26. }

GO代码实现:

  1. func sortedArrayToBST(nums []int) *TreeNode {
  2. return helper(nums, 0, len(nums) - 1)
  3. }
  4. func helper(nums []int, left, right int) *TreeNode {
  5. if left > right {
  6. return nil
  7. }
  8. mid := (left + right) / 2
  9. root := &TreeNode{Val: nums[mid]}
  10. root.Left = helper(nums, left, mid - 1)
  11. root.Right = helper(nums, mid + 1, right)
  12. return root
  13. }