llllmz

导航

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

如果按一般思路建一个平衡二叉树,非常麻烦。

但是二分查找树就一个平衡二叉树,所有构建二叉查找树就行。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct  TreeNode* bulid(int* nums,int head,int tail){
    if(head>tail) return NULL;
    int mid=(head+tail)/2;
    struct TreeNode* temp=(struct TreeNode*)malloc(sizeof(struct TreeNode));
    temp->val=nums[mid];
    temp->left=bulid(nums,head,mid-1);
    temp->right=bulid(nums,mid+1,tail);
    return temp;
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    if(numsSize<1) return NULL;
    int head=0,tail=numsSize-1;
    return bulid(nums,head,tail);
}

结果:

posted on 2024-03-07 15:09  神奇的萝卜丝  阅读(24)  评论(0)    收藏  举报