1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package mrzhang.leecode;
public class Solution108 {
public static TreeNode sortedArrayToBST(int[] nums) { return dfs(nums, 0, nums.length - 1); }
private static TreeNode dfs(int[] nums, int left, int right) { if (left > right) { return null; } int mid = left + (right - left) / 2; TreeNode root = new TreeNode(nums[mid]); root.left = dfs(nums, left, mid - 1); root.right = dfs(nums, mid + 1, right); return root; }
public static void main(String[] args) { int[] nums = {-10,-3,0,5,9}; TreeNode root = sortedArrayToBST(nums); TreeNode.prePrint(root); }
}
|