[LeetCode] 108. Convert Sorted Array to Binary Search Tree
Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
Example 1:
Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3] Output: [3,1] Explanation: [1,3] and [3,1] are both a height-balanced BSTs.
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in a strictly increasing order.
将有序数组转化为二叉搜索树。
给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。
高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目即是题意。只要输出一个有效的BST即可。此题可以跟109题一起做,要求很接近但是做法不太一样。
这个题可以用递归做。因为是BST的关系,而且input是有序数组,如果熟练,就会想到中序遍历BST的output就是一个有序数组。思路是找到数组的mid元素,即是找到了BST的根节点。小于根节点的节点是左孩子,反之是右孩子。但是注意中序遍历的结果并不能确定唯一的BST。代码如下
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public TreeNode sortedArrayToBST(int[] nums) { 3 // corner case 4 if (nums == null || nums.length == 0) { 5 return null; 6 } 7 return helper(nums, 0, nums.length - 1); 8 } 9 10 private TreeNode helper(int[] nums, int left, int right) { 11 if (left > right) 12 return null; 13 int mid = left + (right - left) / 2; 14 TreeNode root = new TreeNode(nums[mid]); 15 root.left = helper(nums, left, mid - 1); 16 root.right = helper(nums, mid + 1, right); 17 return root; 18 } 19 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {TreeNode} 4 */ 5 var sortedArrayToBST = function (nums) { 6 if (nums == null || nums.length == 0) return null; 7 return helper(nums, 0, nums.length - 1); 8 } 9 10 var helper = function (nums, low, high) { 11 if (low > high) return null; 12 var mid = parseInt((high + low) / 2); 13 var root = new TreeNode(nums[mid]); 14 root.left = helper(nums, low, mid - 1); 15 root.right = helper(nums, mid + 1, high); 16 return root; 17 }
相关题目
108. Convert Sorted Array to Binary Search Tree
109. Convert Sorted List to Binary Search Tree