LeetCode 108: Convert Sorted Array to Binary Search Tree

/**
 * 108. Convert Sorted Array to Binary Search Tree
 * 1. Time:O(n)  Space:O(n)
 * 2. Time:O(n)  Space:O(n)
 */

// 1. Time:O(n)  Space:O(n)
class Solution {
    private int[] nums;
    public TreeNode sortedArrayToBST(int[] nums) {
        this.nums = nums;
        return helper(0,this.nums.length-1);
    }
    
    private TreeNode helper(int left, int right){
        if(left>right) return null;
        int mid = (left+right)/2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(left,mid-1);
        root.right = helper(mid+1,right);
        return root;
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    
    private class MyTreeNode{
        TreeNode root;
        int start;
        int end;
        
        public MyTreeNode(TreeNode root, int start, int end){
            this.root = root;
            this.start = start;
            this.end = end;
        }
    }
    
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums==null || nums.length==0) return null;
        Stack<MyTreeNode> stack = new Stack<>();
        int start = 0;
        int end = nums.length;
        int mid = (start+end) >>> 1;
        TreeNode root = new TreeNode(nums[mid]);
        TreeNode cur = root;
        stack.push(new MyTreeNode(root,start,end));
        while(!stack.isEmpty() || end-start>1){
            while(end-start>1){
                mid = (start+end) >>> 1;
                end = mid;
                mid = (start+end) >>> 1;
                cur.left = new TreeNode(nums[mid]);
                cur = cur.left;
                stack.push(new MyTreeNode(cur,start,end));
            }
            MyTreeNode tmp = stack.pop();
            start = tmp.start;
            end = tmp.end;
            mid = (start+end) >>> 1;
            cur = tmp.root;
            start = mid + 1;
            if(start<end){
                mid = (start+end) >>> 1;
                cur.right = new TreeNode(nums[mid]);
                cur = cur.right;
                stack.push(new MyTreeNode(cur,start,end));
            }
        }
        return root;
    }
}
posted @ 2020-05-07 11:57  AAAmsl  阅读(86)  评论(0编辑  收藏  举报