welcome to my blog
LeetCode Top Interview Questions 108. Convert Sorted Array to Binary Search Tree (Java版; Easy)
题目描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
第一次做; 核心: 为了让树平衡, 所以让数组的中点作为根节点,数组中点的左边也这样处理, 数组中点的右边也这样处理,所以自然地使用递归实现; 关键还是要明白搜索二叉树的定义:对于树上的任意一个节点node, 如果node左子树的值都比node.val小, node右子树的值都比node.val大, 那么该树就是搜索二叉树; 细节:要明白递归函数base case中的if(left>right)的发生条件, 比如上一轮L=0,R=1时此时M=0,那么调用root.left=core(nums,L,M-1)=core(nums,0,-1)就会出现left>right的情况
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null || nums.length==0)
return null;
//
return core(nums, 0, nums.length-1);
}
//递归函数逻辑:将[left,right]的值构造成搜索二叉树, 为了实现平衡特性,让nums[mid]作为根节点的值, 根节点连接左子树[left,mid-1]的根节点,根节点连接右子树[mid+1,right]的根节点,最后返回根节点; 因为用到了左右子树的根节点信息, 所以自己也得返回根节点
public TreeNode core(int[] nums, int left, int right){
//base case
if(left==right)
return new TreeNode(nums[left]);
//上一轮递归中L=0,R=1, 那么M-1=-1
if(left>right)
return null;
//
int mid = left + ((right-left)>>1);
TreeNode root = new TreeNode(nums[mid]);
root.left = core(nums, left, mid-1);
root.right = core(nums, mid+1, right);
return root;
}
}