package Level2;
import Utility.TreeNode;
/**
* Convert Sorted Array to Binary Search Tree
*
* Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
*/
public class S108 {
public static void main(String[] args) {
int[] num = {1,3};
TreeNode n = sortedArrayToBST(num);
n.print();
}
public static TreeNode sortedArrayToBST(int[] num) {
return sortedArrayToBSTRec(num, 0, num.length-1);
}
// 二分查找节点值,并递归创建节点
private static TreeNode sortedArrayToBSTRec(int[] num, int low, int high){
if(low > high){
return null;
}
int mid = low + (high-low)/2; // 找到中值
TreeNode root = new TreeNode(num[mid]); // 创建根节点
root.left = sortedArrayToBSTRec(num, low, mid-1); // 递归创建左子树和右子树
root.right = sortedArrayToBSTRec(num, mid+1, high);
return root;
}
}
Convert Sorted Array to Binary Search Tree @LeetCode
最新推荐文章于 2021-11-02 12:48:41 发布
介绍如何将一个升序排列的整数数组转换为一棵高度平衡的二叉搜索树(BST)。通过递归地选取数组中间元素作为根节点,并继续对左右子数组进行相同操作来构建树。
371

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



