Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return solve(nums, 0, nums.length-1);
}
private TreeNode solve(int[] nums, int s, int e) {
if (s > e) {
return null;
}
int mid = (s+e)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = solve(nums, s, mid-1);
root.right = solve(nums, mid+1, e);
return root;
}
}
本文介绍了一种将有序数组转换为高度平衡二叉搜索树(BST)的方法。通过递归地选择中间元素作为根节点,并将左右两侧的子数组分别转换为左子树和右子树,可以确保树的高度平衡。
343

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



