一、题目
给定一个有序整数数组,元素各不相同且按升序排列,编写一个算法,创建一棵高度最小的二叉搜索树。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
二、C# 题解
很基础的题目了。递归中序遍历构建二叉树:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode SortedArrayToBST(int[] nums) {
return Partition(nums, 0, nums.Length);
}
public TreeNode Partition(int[] nums, int left, int right) {
if (left == right) return null;
int mid = (left + right) / 2;
TreeNode node = new TreeNode(nums[mid]); // 中间元素作为头结点
node.left = Partition(nums, left, mid); // 左孩子为左方区间处理结果
node.right = Partition(nums, mid + 1, right); // 右孩子为右方区间处理结果
return node;
}
}
- 时间复杂度: O ( n ) O(n) O(n)。
- 空间复杂度: O ( log n ) O(\log n) O(logn)。