Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
方法一:把鏈表裏的元素放入數組,再進行查找
方法二:遍歷鏈表,設置快慢指針,找到中間元素,將該元素作爲根節點時間複雜度爲O(NlgN)
萬能的遞歸法,注意到有一點比較巧的是,由於單鏈表都是單向的。所以這裏我的查找區間設置爲左閉右開!這樣就避免了去找mid節點的前一個節點
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
return create(head,nullptr);
}
TreeNode* create(ListNode* head, ListNode* tail) {
if(head == tail)
return nullptr;
ListNode* fast = head;
ListNode* slow = head;
while(fast != tail && fast->next != tail) {
fast = fast->next->next;
slow = slow->next;
}
TreeNode* root = new TreeNode(slow->val);//不能直接將listnode指針賦值給treenode
root->left = create(head,slow);
root->right = create(slow->next,tail);
return root;
}
};