码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Convert Sorted List to Binary Search Tree (middle)

时间:2015-01-18 21:03:17      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

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

 

思路:题目看上去好像很难,但实际上很简单,递归做就行,每次找到左右子树对应的子链表就行。一次AC。

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL)
            return NULL;

        ListNode * fast = head, *slow = head, *slowpre = head; //分别是快指针、慢指针、慢指针前一个指针 慢指针的位置就是当前平衡树根节点的位置 中间值
        while(fast != NULL && fast->next != NULL)
        {
            fast = fast->next->next;
            slowpre = slow;
            slow = slow->next;    
        }
        TreeNode * root = new TreeNode(slow->val);
        ListNode * left = (slow == head) ? NULL : head; //如果慢指针==头指针 则其左子树是空的
        ListNode * right = slow->next;
        slowpre->next = NULL; //左子树对应的链表末尾置null
        root->left = sortedListToBST(left);
        root->right = sortedListToBST(right);

        return root;
    }
};

 

【leetcode】Convert Sorted List to Binary Search Tree (middle)

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4232230.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!