Java Recursive Solution,Very Easy to Understand


  • 0
    R
    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            if (nums.length == 0)
    			return null;
    		return fun(nums, 0, nums.length - 1);
        }
        static TreeNode fun(int[] nums, int begin, int end) {
    		int mid = begin + (end - begin) / 2;
    		TreeNode root = new TreeNode(nums[mid]);
    		if (mid > begin)
    			root.left = fun(nums, begin, mid - 1);
    		if (mid < end)
    			root.right = fun(nums, mid + 1, end);
    		return root;
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.