109-Convert Sorted List to Binary Search Tree

题目

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

分析

这个和Covert Sorted Array to Binary Search Tree 其实是类似的,都是通过递归构造

关键就在于如何找到链表的中间结点。

链表的中间结点可以用快慢指针来实现。

处理的时候要比较细心,有三种情况
1. 头尾指针指向同一个结点
2. 头尾指针指向相邻结点
3. 头尾指针中间间隔的结点>= 2个

实现
class Solution {
public:
    //109. Convert Sorted List to Binary Search Tree
    TreeNode* sortedListToBST(ListNode* head) {
        if (!head)
            return NULL;
        return  sortedListToBSTHelper(head, NULL);

    }
    TreeNode* sortedListToBSTHelper(ListNode* start, ListNode* end)
    {   

        //指向同一个结点
        if (start == end)
            return NULL;
        //指向相邻结点
        if (start->next == end)
        {
            TreeNode *root = new TreeNode(start->val);
            return root;
        }
        ListNode *slow = start, *fast = start;
        //指向不相邻结点
        while (fast->next != end&&fast->next->next != end)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        TreeNode * root = new TreeNode(slow->val);
        root->left = sortedListToBSTHelper(start, slow);
        root->right = sortedListToBSTHelper(slow->next, end);
        return root;



    }

};

你可能感兴趣的:(Leetcode,算法题解,c++,链表,二叉树建立)