解法都在代码里,不懂就留言或者私信
java
/**
* 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 {
/**二叉搜索树的特征:某个节点的左子树的所有节点都小于它,右子树的所有节点的值都大于它
我们先找到中间的那个数的下标mid,然后0~mid-1 构造左子树,mid+1~end构造右子树 */
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode root = generateBST(nums, 0, nums.length - 1);
return root;
}
public TreeNode generateBST(int[] nums, int left, int right) {
/**没有数别捣乱了 */
if(left > right) {
return null;
}
/**如果就一个数,那就构造呗 */
if(left == right) {
return new TreeNode(nums[left]);
}
/**大于1个数找到中间那个点 */
int mid = left + ((right - left) >> 1);
/**构造根节点 */
TreeNode root = new TreeNode(nums[mid]);
/**左边是它的左子树 */
root.left = generateBST(nums, left, mid - 1);
/**右边是它的右子树 */
root.right = generateBST(nums, mid + 1, right);
return root;
}
}
运行结果,规定压栈占空间,这里可以优化,我时间不够就算了