# 5 Convert Sorted List to Binary Search Tree_Leetcode

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

（1）dummy节点的使用可以帮助找到中点的prev节点

（2）边界情况

Code:

/**
* 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:
}

{

ListNode* dummy = new ListNode(0);
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;
}
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;
}
};


posted @ 2014-10-16 20:52  Avril  阅读(182)  评论(0编辑  收藏