*LeetCode-Convert Sorted Array to Binary Search Tree

直观的就是recursive方法 每次取中间的数字做root 左右分别做

一开始用的方法用本函数递归了 就不能传index 只能传subarray 就废了空间因为要copy

后来看了一眼去年写的 应该写一个传本array和start end的helper函数来递归

public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if ( nums == null || nums.length == 0 )
            return null;
        return helper ( nums, 0, nums.length - 1 );

    }
    public TreeNode helper ( int[] nums, int start, int end ){
        if ( start < 0 || end >= nums.length || start > end )
            return null;
        int mid = start + ( end - start ) / 2;
        TreeNode root = new TreeNode ( nums [ mid ] );
        TreeNode left = helper ( nums, start, mid - 1 );
        TreeNode right = helper ( nums, mid + 1, end );
        root.left = left;
        root.right = right;
        return root;
    }
}

还有iterative的方法 就是需要用inorder traversal

需要用stack

你可能感兴趣的:(*LeetCode-Convert Sorted Array to Binary Search Tree)