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; } }