Simple C# solution with comments


  • 0
    *

    public class Solution {
    public TreeNode SortedArrayToBST(int[] nums) {

    	if(nums.Count() < 1)
    		return null;
    	
    	int mid = nums.Count()/2;
    	TreeNode root = new TreeNode(nums[mid]);
    	
    	// Odd elements: left.length == right.length
    	// Even elements: left.length > right.length  
    	int[] leftArray = new int[mid]; 			
    	Array.Copy(nums, 0, leftArray, 0, mid);	
    	root.left = SortedArrayToBST(leftArray);
    	
    	// RightLen: This will work in case of even and odd len, as we subtract from nums;
    	int rightLen = nums.Length - 1 - leftArray.Length; 	
    	if( rightLen > 0)
    	{
    		int[] rightArray = new int[rightLen];
    		Array.Copy(nums, mid+1, rightArray, 0, rightLen);	
    		root.right = SortedArrayToBST(rightArray);
    	}
    	return root;
    }
    

    }


Log in to reply
 

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