题目原文:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题目大意:
把一个升序排列的数组构建成BST(二叉排序树)。
题目分析:
数组的中点是二叉排序树的根节点,然后递归把左半边和右半边递归构建成左子树和右子树。
源码:(language:java)
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length==0)
return null;
TreeNode bst=createBST(nums,0,nums.length-1);
return bst;
}
public TreeNode createBST(int[] nums,int start,int end) {
int mid = (start + end) / 2;
TreeNode root = new TreeNode(nums[mid]);
if(start < mid )
root.left = createBST(nums,start,mid-1);
if(mid < end)
root.right = createBST(nums,mid+1,end);
return root;
}
}
成绩:
1ms,beats 7.24%,众数1ms,92.62%
本文介绍了一种将升序数组转换为高度平衡二叉搜索树的方法。通过选取数组中间元素作为根节点,并递归地将左右两侧的子数组构造成左右子树,最终形成平衡的二叉树。
1019

被折叠的 条评论
为什么被折叠?



