Convert Sorted Array to Binary Search Tree With Minimal Height.
Description
Given a sorted (increasing order) array, Convert it to a binary search tree with minimal height.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param A: an integer array
* @return: A tree node
*/
public TreeNode sortedArrayToBST(int[] A) {
// write your code here
if(A == null){
return null;
}
int n = A.length - 1 ;
return toBST(A, 0 , n) ;
}
public TreeNode toBST(int[] A , int L , int R){
if(L > R){
return null ;
}
int mid = (L + R) >>>1 ;
TreeNode left = toBST(A, L , mid-1);
TreeNode curt = new TreeNode(A[mid]);
curt.left = left ;
TreeNode right = toBST(A, mid+1 , R);
curt.right = right ;
return curt ;
}
}
最小高度二叉搜索树构造
该博客讨论如何从有序数组构建最小高度的二叉搜索树。解决方案通过递归地将数组分成左右子数组来实现,每次选择中间元素作为根节点,确保平衡。
9840

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



