题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
天气太热了,不写分析 直接java代码:
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return buildTree(nums,0,nums.length-1);
}
public TreeNode buildTree(int []nums,int left,int right){
if(left>right)
return null;
if(left==right)
return new TreeNode(nums[left]);
int mid = (left+right)/2;
TreeNode node = new TreeNode(nums[mid]);
node.left=buildTree(nums,left,mid-1);
node.right=buildTree(nums,mid+1,right);
return node;
}
}