Discription:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
我的解法:
TreeNode* sortedListToBST(ListNode* head) {
if (!head) return NULL;
if (!head->next){
TreeNode *root = new TreeNode(head->val);
return root;
}
ListNode *pfast = head->next, *pslow = head, *head2;
while (pfast->next && pfast->next->next){
pfast = pfast->next->next;
pslow = pslow->next;
}
head2 = pslow->next->next;
TreeNode *root = new TreeNode(pslow->next->val);
pslow->next = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(head2);
return root;
}
Leetcode上参考解法:
TreeNode* sortedListToBST(ListNode* head) {
if (head == NULL)
return NULL;
ListNode *fast = head;
ListNode *slow = head;
ListNode *prev = NULL;
while (fast && fast->next)
{
fast = fast->next->next;
prev = slow;
slow = slow->next;
}
TreeNode *root = new TreeNode(slow->val);
if (prev)
prev->next = NULL;
else
head = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}