将有序单链表转化为平衡二叉树

109. Convert Sorted List to Binary Search Tree

struct TreeNode* constr(struct ListNode* head,struct ListNode* tail)
{
    if(head==tail) return NULL;
    struct ListNode *mid=head,*temp=head;
    while(temp!=tail&&temp->next!=tail)
    {
        temp=temp->next->next;
        mid=mid->next;
    }
    struct TreeNode *T=(struct TreeNode*)malloc(sizeof(struct TreeNode));
    T->val=mid->val;
    T->left=constr(head,mid);
    T->right=constr(mid->next,tail);
    return T;
}
struct TreeNode* sortedListToBST(struct ListNode* head) {
    struct TreeNode *root=constr(head,NULL);
    return root;
}
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/gl486546/article/details/77163910
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞