原题网址: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.
方法:递归,自顶向下。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode build(int[] nums, int from, int to) {
if (from>to) return null;
int m = (from+to)/2;
TreeNode root = new TreeNode(nums[m]);
root.left = build(nums, from, m-1);
root.right = build(nums, m+1, to);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
return build(nums, 0, nums.length-1);
}
}

介绍了一种将已排序的数组转换为高度平衡的二叉搜索树的方法。通过递归方式,从数组中间元素开始构建根节点,并以此递归左右子数组,确保构建出的树具有良好的平衡性。
662

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



