Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
if(num.length == 0)
return null;
return build(num, 0, num.length - 1);
}
public TreeNode build(int[] num, int s, int e){
if(s > e)
return null;
int m = (s + e) / 2;
TreeNode root = new TreeNode(num[m]);
root.left = build(num, s, m - 1);
root.right = build(num, m + 1, e);
return root;
}
}

本文介绍了一种方法,通过给定的升序排序数组构建一个高度平衡的二叉搜索树(BST)。具体实现涉及递归构建树节点,确保树的高度平衡。
1334

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



