对排好序的数组二分,中点就是root,左边部分左子树,右边部分右子树
public class Solution { //Time: O(n) public TreeNode sortedArrayToBST(int[] num) { if (num == null || num.length == 0) { return null; } return convert(num, 0, num.length - 1); } private TreeNode convert(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 = convert(num, start, mid - 1); root.right = convert(num, mid + 1, end); return root; } }
No comments:
Post a Comment