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

来源:互联网 发布:鸡兔同笼java语言编程 编辑:程序博客网 时间:2023/02/03 02:28

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;}
原创粉丝点击