-
-
Save jason51122/471a22c93c3f65a663c6 to your computer and use it in GitHub Desktop.
4.3 Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { | |
val = x; | |
} | |
} | |
public TreeNode sortedArrayToBST(int[] num) { | |
if (num == null || num.length == 0) { | |
return null; | |
} | |
return helper(num, 0, num.length - 1); | |
} | |
private TreeNode helper(int[] num, int start, int end) { | |
if (start > end) { | |
return null; | |
} | |
int mid = start + (end - start) / 2; | |
TreeNode root = new TreeNode(num[mid]); | |
root.left = helper(num, start, mid - 1); | |
root.right = helper(num, mid + 1, end); | |
return root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment