108. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5
因为BST是有序的,比当前节点小的都放在左子树,比当前节点大的都放在右子树,然后要求是balanced,左右子树的深度不能相差超过1,所以考虑用二分的方法,每次找vector中间的数作为根,然后把左半边的vector作为左子树,继续找中间的数;右半边的vector作为右子树,继续找中间的数。。。依次类推,构建出一棵树。

大体思路是清晰的,但是细节还是有很多问题。

1 使用递归,构建当前子树然后返回根

2 mid = (low + high + 1) / 2, 一定要记得+1,不然到最后的边界会有问题

3 递归函数的参数如何选择,需要用mid - 1代替high, mid+1 代替low,不然会有节点重复的现象

4 什么时候终止递归,这个很重要,每次想的都不是太清楚。这道题是当mid == low时直接把左子树设为NULL,而不继续调用递归函数;当mid == high 时,把右子树设为NULL,而不继续调用递归函数。

用例子 [-10, -3, 0, 5, 9] 做一个状态转移,分析一下边界问题,和终止条件:





















代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* builtTree(vector<int> nums, int low, int high) {
        int mid = (high + low + 1) / 2; //remember to +1 or mid will be wrong
        TreeNode* root = new TreeNode(nums[mid]);
        if (mid == low) root->left = NULL; // terminal condition
        else root->left = builtTree(nums, low, mid - 1); // mid - 1 instead of mid or node will repeat
        if (mid == high) root->right = NULL; // terminal condition
        else root->right = builtTree(nums, mid + 1, high); // mid + 1 same as mid - 1
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if (nums.size() == 0) return NULL;
        if (nums.size() == 1) {
            TreeNode* root = new TreeNode(nums[0]);
            return root;
        }
        return builtTree(nums, 0, nums.size() - 1);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值