二叉搜索树的中序遍历是升序序列
如果知道了二叉搜索树的中序遍历,但没有指定高度平衡,可能的二叉搜索树有很多种。
首先确定二叉搜索树的根节点,选取中间数字作为根节点,对于奇数会很方便,对于偶数,选取中间数字的左边或者右边。
数组的下标范围为从【left,right】,选取中间数字的左边为根节点,则mid = (left+right)/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) {
//注意:right的值为nums.length-1
return helper(nums,0,nums.length-1);
}
public TreeNode helper(int[] nums, int left, int right){
if(left > right){
return null;
}
int mid = (left+right) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums,left,mid -1);
root.right = helper(nums,mid+1,right);
return root;
}
}