Thought:
The middle position of the array will be the root.
All left elements will be the left subtree.
All right elements will be the right subtree.
Code:
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
int len = num.length;
if(len == 0) return null;
TreeNode root = new TreeNode(num[len/2]);
root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, len/2));
root.right = sortedArrayToBST(Arrays.copyOfRange(num, len/2 + 1, len));
return root;
}
}
No comments:
Post a Comment