Java Code:
public TreeNode sortedArrayToBST(int[] num) {
return sortedSubArrayToBST(num, 0, num.length-1);
}
public TreeNode sortedSubArrayToBST(int[] num, int begin, int end){
if( begin > end) return null;
int middle = (begin+end)/2;
TreeNode root = new TreeNode(num[middle]);
root.left = sortedSubArrayToBST(num, begin, middle-1);
root.right = sortedSubArrayToBST(num, middle+1, end);
return root;
}
This comment has been removed by the author.
ReplyDeleteThank you for the example, I have seen similar code structure to build this bst but it didn't work because it did not have the last two if statement. That was important.
ReplyDelete