Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.數組
1.解題思路
平衡二叉樹,其實就是數組中間的數做爲根,利用遞歸實現左子樹和右子樹的構造。code
2.代碼遞歸
public class Solution { public TreeNode sortedArrayToBST(int[] nums) { return helper(0,nums.length-1,nums); } private TreeNode helper(int start,int end,int[] nums){ if(start>end) return null; int mid=start+(end-start)/2; TreeNode root=new TreeNode(nums[mid]); root.left=helper(start,mid-1,nums); root.right=helper(mid+1,end,nums); return root; } }