二叉搜索树的中序遍历是升序序列
选择中间数字作为根节点,可以保持树的平衡
mid = left + (right - left)/2;这种求中间数的方式可以防止数的溢出
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return dfs(nums,0,nums.length - 1);
}
TreeNode dfs(int[] nums,int left,int right){
if(left <= right){
int mid = left + (right - left)/2;
TreeNode node = new TreeNode(nums[mid]);
node.left = dfs(nums,left,mid - 1);
node.right = dfs(nums, mid + 1,right);
return node;
}
return null;
}
}