leetcode【DFS】-----109. Convert Sorted List to Binary Search Tree(有序链表转为二叉树)

1、题目描述

     

2、分析

        之前做过将一个有序数组转化为二叉树,这道题可以先将链表转化为数组,然后再将数组转化为二叉树,不过这样太过于复杂。因为数组的中点更容易找,但是这里可以通过快慢指针的方法来找到链表的中点,之后和前面构造二叉树的方法一样分为两部分,递归构造。

3、代码

/**
 * 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:
    ListNode* findmid(ListNode* head) {
        ListNode* fast=head;
        ListNode* slow=head;
        ListNode* prenode = NULL;
        while(fast!=NULL&&fast->next!=NULL){
            prenode=slow;
            fast=fast->next->next;
            slow=slow->next;
        }
        if(prenode!=NULL){
            prenode->next=NULL;
        }
        return slow;
        
    }
     TreeNode* sortedListToBST(ListNode* head) {
        if(head==NULL) return NULL;
        ListNode* mid=findmid(head);
        TreeNode* Treehead=new TreeNode(mid->val);
        if(head==mid) return Treehead;
        Treehead->left=sortedListToBST(head);
        Treehead->right=sortedListToBST(mid->next);
        return Treehead;
         
    }
};

4、相关知识点

        链表找到中间结点的技巧。

posted @ 2019-07-09 21:03  吾之求索  阅读(96)  评论(0)    收藏  举报