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

【leetcode】Convert Sorted List to Binary Search Tree-递

时间:2014-09-09 12:56:58      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:io   ar   on   c   amp   ad   new   ef   bs   

我觉着写得比看到的答案更清晰~

class Solution {
public:
    TreeNode *ltob(ListNode *head, ListNode *end) {
        if(head == end) {
            TreeNode * node = new TreeNode(head->val);
            return node;
        }
        ListNode *slow = head, *fast = head, *pre = NULL;
        while(fast != end && fast->next != end) {
            pre = slow, slow = slow->next, fast = fast->next->next;
        }
        TreeNode *node = new TreeNode(slow->val);
        if(pre) node->left = ltob(head, pre);
        node->right = ltob(slow->next,end);
        return node;
    }
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL) return NULL;
        ListNode *end = head;
        while(end->next) end = end->next;
        return ltob(head, end);
    }
};



【leetcode】Convert Sorted List to Binary Search Tree-递

标签:io   ar   on   c   amp   ad   new   ef   bs   

原文地址:http://blog.csdn.net/cx351864995/article/details/39140381

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