Skip to content

[LeetCode] 108. 将有序数组转换为二叉搜索树 #30

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

Open
Animenzzzz opened this issue Aug 7, 2019 · 0 comments
Open

[LeetCode] 108. 将有序数组转换为二叉搜索树 #30

Animenzzzz opened this issue Aug 7, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定有序数组: [-10,-3,0,5,9],

一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

解题思路:二叉搜索树的中序遍历就是一个有序的串。使用二分法。参考题目下的解答

C解题:

struct TreeNode* balance(int* nums, int begin,int end){
    if(begin > end) return NULL;
    int mid = begin+(end-begin)/2;
    struct TreeNode* root = (struct TreeNode*)calloc(1,sizeof(struct TreeNode));
    root->val = nums[mid];
    root->left = balance(nums,begin,mid-1);
    root->right = balance(nums,mid+1,end);
    return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
    return balance(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