Leetcode每日一题打卡

108.将有序数组转换为平衡二叉树

原题

采用中序遍历,中间位置的数值作为根节点,左边(left)即是左子树,右边(right)是右子树,递归计算出搜索二叉树,在left>right时返回空指针。

/**
 * 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 {
    TreeNode* root;
public:
    TreeNode* getTree(vector<int>& nums, int left, int right, TreeNode* r) {
        if(left>right) return nullptr;
        int mid=(right+left)/2;
        r=new TreeNode(nums[mid]);
        r->left=getTree(nums, left, mid-1, r->left);
        r->right=getTree(nums,mid+1,right,r->right);
        return r;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        TreeNode* root;
        int n=nums.size();
        if(n==0) return nullptr;
        return getTree(nums, 0, n-1, root);
    }
};

时间复杂度O(n)。空间复杂度O(logn)(递归栈消耗)。

你可能感兴趣的:(Leetcode每日一题打卡,leetcode)