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.
Subscribe to see which companies asked this question
参考链接:
方法一、http://www.2cto.com/kf/201402/282179.html
方法二、http://www.cnblogs.com/ganganloveu/p/4061909.html
更简洁的博客:http://blog.youkuaiyun.com/worldwindjp/article/details/39722643
//时间复杂度为O(nlgn)的方法
ListNode* findMid(ListNode* head)
{
ListNode* slowTail = NULL;
ListNode* slow = head;
ListNode* fast = head;
while(fast)
{
fast = fast->next;
if(fast)
{
fast = fast->next;
slowTail = slow;
slow = slow->next;
}
}
slowTail->next = NULL;//把链表分为两个部分
return slow;
}
TreeNode* sortedListToBST(ListNode* head) {
if(NULL == head)
{
return NULL;
}
else if(NULL == head->next)
{
return new TreeNode(head->val); //改成这种写法,而不是TreeNode* temp; temp->val = head->val; return temp;则就不会报runtime 错误
}
ListNode* mid = findMid(head);
TreeNode* root = new TreeNode(mid->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(mid->next);
return root;
}