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

5 Convert Sorted List to Binary Search Tree_Leetcode

时间:2014-10-16 22:31:43      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   for   sp   div   

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

这题和sort list等题都比较相似,需要先用快慢指针的方法找到链表的中点,然后用recursive的方式构建左子树和右子树(用到的思想是Divide&Conquer),然后再构建好这个节点。

编程时一点要注意:

(1)dummy节点的使用可以帮助找到中点的prev节点

但是dummy节点只有当用时再构造,建议不要提前建好当参数传进来,会非常不清晰。用完后最后记得delete,否则会memory leak. 也不能delete得过早,因为prev可能等于dummy.

(2)边界情况

当middle节点为head时,应注意,左子树为NULL,不要递归build。

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if(!head) return NULL;
        TreeNode* treeHead = buildTree(head);
        return treeHead;
    }
    
    TreeNode* buildTree(ListNode *head)
    {
        if(!head) return NULL;
        if(!head->next) return new TreeNode(head->val);
        
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* prev = dummy, *slow = dummy->next, *fast = dummy->next->next;
        while(fast && fast->next)
        {
            slow = slow->next;
            prev = prev->next;
            fast = fast->next->next;
        }

        TreeNode* cur = new TreeNode(slow->val);
        
        TreeNode* left, *right;  // second error, cannot initialize left in the if-else
        right = buildTree(slow->next);
        if(prev != dummy)      // first error
        {
            prev->next = NULL;
            left = buildTree(head);
        }
        else left = NULL;
        
        cur->left = left;
        cur->right = right;
        
        delete dummy;  // first error, can not delete dummy too early if prev equals dummy
        
        return cur;
    }
};

  

5 Convert Sorted List to Binary Search Tree_Leetcode

标签:style   blog   color   io   使用   ar   for   sp   div   

原文地址:http://www.cnblogs.com/avril/p/4029663.html

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