recursive O(n) time
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Solution { public: Node* flatten(Node* head) { Node dummy_head; dummy_head.next = head; helper(head); return dummy_head.next; }
Node *helper(Node *head) { if (!head) return head; if (head->child) { auto succ = head->next; head->next = head->child; head->child = nullptr; head->next->prev = head; auto prev = helper(head->next); prev->next = succ; if (succ) { succ->prev = prev; } } return head->next ? helper(head->next) : head; } };
|
iterative O(n) time
每个node访问两次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
class Solution { public: Node* flatten(Node* head) { for (auto p = head; p; p = p->next) { if (p->child) { auto succ = p->next; p->next = p->child; p->next->prev = p; p->child = nullptr; auto tail = p->next; while (tail->next) { tail = tail->next; } tail->next = succ; if (succ) { succ->prev = tail; } } } return head; } };
|