Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

108. 将有序数组转换为二叉搜索树 #205

Open
hey-monster opened this issue May 9, 2022 · 0 comments
Open

108. 将有序数组转换为二叉搜索树 #205

hey-monster opened this issue May 9, 2022 · 0 comments

Comments

@hey-monster
Copy link
Owner

hey-monster commented May 9, 2022

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。

高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。

 

示例 1:

输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:

示例 2:

输入:nums = [1,3]
输出:[3,1]
解释:[1,null,3] 和 [3,1] 都是高度平衡二叉搜索树。
 

提示:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums 按 严格递增 顺序排列

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:递归

void initNode(struct TreeNode** p, int value){
    (*p) = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    (*p)->val = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}
void Dfs(int* nums, struct TreeNode* node, int l1, int l2, int r1, int r2){
    if(l1 > l2 && r1 > r2){
        return;
    }
    if(l1 <= l2){
        int mid = l1 + (l2 - l1) / 2;
        initNode(&node->left, nums[mid]);
        Dfs(nums, node->left, l1, mid - 1, mid + 1, l2);
    }
    if(r1 <= r2){
        int mid = r1 + (r2 - r1) / 2;
        initNode(&node->right, nums[mid]);
        Dfs(nums, node->right, r1, mid - 1, mid + 1, r2);
    }
    return;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
    int mid = numsSize / 2;
    struct TreeNode* root = NULL;
    initNode(&root, nums[mid]);
    struct TreeNode* current = root;

    int left1 = 0;
    int left2 = mid - 1;
    int right1 = mid + 1;
    int right2 = numsSize - 1;
    Dfs(nums, current, left1, left2, right1, right2);
    return root;
}
struct TreeNode* helper(int* nums, int left, int right) {
    if (left > right) {
        return NULL;
    }

    // 总是选择中间位置左边的数字作为根节点
    int mid = (left + right) / 2;

    struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->val = nums[mid];
    root->left = helper(nums, left, mid - 1);
    root->right = helper(nums, mid + 1, right);
    return root;
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    return helper(nums, 0, numsSize - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant