Fork me on GitHub

[leetcode-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.

思路:利用快慢指针找到中间节点,作为根节点,然后左子树即为左边链表部分,右子树即为右边链表部分,递归进行即可。

TreeNode* sortedListToBST(ListNode* head)
    {
        //利用fast 和 slow 指针 找到链表中点
        return build(head,NULL);
    }
    TreeNode* build(ListNode* start, ListNode* end)
    {
        if (start == end)
        {
            return NULL;
        }
        ListNode* fast = start;
        ListNode* slow = start;
        while (fast != end && fast->next != end)//注意第一次执行的时候end为NULL 没毛病。。
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        TreeNode* node = new TreeNode(slow->val);
        node->left = build(start, slow);
        node->right = build(slow->next, end);
        return node;    
    }

参考:

https://siddontang.gitbooks.io/leetcode-solution/content/tree/convert_sorted_listarray_to_binary_search_tree.html

posted @ 2017-03-26 23:27  hellowOOOrld  阅读(849)  评论(0编辑  收藏  举报