题目来源
面试题 04.02. 最小高度树
108. 将有序数组转换为二叉搜索树
小心,这题很容易出错
题目描述
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
}
};
题目解析
思路:
- 如果序列长度为 0,那么是一棵空树。
- 如果序列长度为 1,那么只有一个根节点。
- 如果长度大于 1,那么选取中间位置的数赋给根节点,然后前一半递归构建左子树,后一半递归构建右子树。
代码:
- cpp
class Solution {
public:
TreeNode *helper(vector<int>& nums, int low, int high){
if(low > high){
return NULL;
}
if(low == high){
return new TreeNode(nums[high]);
}
int mid = low + (high - low) / 2;
TreeNode *node = new TreeNode(nums[mid]);
node->left = helper(nums, low, mid - 1);
node->right = helper(nums, mid + 1, high);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return helper(nums, 0, (int)nums.size() - 1);
}
};
- java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null || nums.length == 0){
return null;
}
TreeNode node = new TreeNode(nums[nums.length / 2]);
node.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, nums.length/2));
node.right = sortedArrayToBST(Arrays.copyOfRange(nums, nums.length/2 + 1, nums.length));
return node;
}
}