将有序数组转为二叉平衡搜索树
解题思路:
二分法。每次取排序数组中间的数作为节点,左边的作为左子节点,右边的作为右子节点,递归直到left>right,才返回。
代码:
public class Solution
{
/*public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{
val = x;
}
}*/
public static TreeNode SortedArrayToBST(int[] nums)
{
return searchtree(0, nums.Length - 1, nums);
}
public static TreeNode searchtree(int left, int right, int[] nums)
{
if (left > right)
return null;
int mid = (left + right) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = searchtree(left, mid - 1, nums);
root.right = searchtree(mid + 1, right, nums);
return root;
}//递归。二分法,每次取中间的数作为根节点。
}