leetcode-有序链表转换二叉搜索树

有序链表转换二叉搜索树

这道题需要定义三个指针,通过快慢指针找出中点,作为根节点,然后从头指针head->指针last这段链表再递归调用sortedListToBST函数,从slow指针下一个节点开始到最后,作为后一个链表再进行递归调用函数sortedListToBST函数。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(head==NULL)
            return NULL;
        ListNode* fast=head;
        ListNode* slow=head;
        ListNode* last=head;
        while(fast->next && fast->next->next)
        {
            last=slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        fast=slow->next;
        last->next=NULL;
        TreeNode *cur=new TreeNode(slow->val);
        if(head!=slow)
            cur->left=sortedListToBST(head);
            cur->right=sortedListToBST(fast);
         return cur;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42063047/article/details/84570988