Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题解:给定一个链表有序的转成平衡BST,关键这里我用额外空间MLE所以应该在链表上直接进行,最优化的应该是设计两个指针,一个slow一个fast用来遍历中间节点,然后左右子树递归建树,代码如下:
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head) return NULL;
ListNode* fast = head, * slow = head, * pre = NULL;
while(fast && fast->next){
fast = fast->next->next;
pre = slow;
slow = slow->next;
}
TreeNode* root = new TreeNode(slow->val);
if(pre != NULL) pre->next = NULL;
else head = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};