【LeetCode】 109. Convert Sorted List to Binary Search Tree C语言

来源:互联网 发布:mac mp3编辑软件 编辑:程序博客网 时间:2024/06/12 00:55

 LeetCode解题心得,欢迎交流! 第三日


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; *//** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */ struct TreeNode *toBST(struct ListNode *head,struct ListNode *tail) {        if(head==tail) return NULL;    struct ListNode *fast=head;    struct ListNode *slow=head;        while(fast!=tail && fast->next!=tail) // 这样写是错的while(fast!=NULL && fast->next!=NULL)    {        fast=fast->next->next;        slow=slow->next;    }        struct TreeNode *tree_head=(struct TreeNode *)malloc(sizeof(struct TreeNode));    tree_head->val = slow->val;    tree_head->left = toBST(head,slow);    tree_head->right=toBST(slow->next,tail);        return tree_head;}struct TreeNode* sortedListToBST(struct ListNode* head) {    if(head == NULL) return NULL;    return toBST(head,NULL);    }


0 0
原创粉丝点击