O(n) time O(1) space
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* connect(Node* root) { Node dummy, *p = &dummy, *res = root; while (root) { if (root->left) { p->next = root->left; p = p->next; } if (root->right) { p->next = root->right; p = p->next; } root = root->next; if (!root) { root = dummy.next; dummy.next = nullptr; p = &dummy; } } return res; } };
|
dfs O(n) time O(h) space
从上往下连,从右往左连,因为上边的连好了下边的才能利用上边的连,右边的连好了左边的才不会连错
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* connect(Node* root) { if (!root) return root; Node dummy_head(0, nullptr, nullptr, nullptr), *tail = &dummy_head; for (auto p = root; p; p = p->next) { if (p->left) { tail->next = p->left; tail = tail->next; } if (tail->next) break; if (p->right) { tail->next = p->right; tail = tail->next; } if (tail->next) break; } connect(root->right); connect(root->left); return root; } };
|
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
|
class Solution { public: void connect(TreeLinkNode *root) { if (!root) return; TreeLinkNode dummy_head(0), *curr = &dummy_head; // 利用dummy_head实现『盲连』,即避免不必要的节点判断 for (auto p = root; p; p = p->next) { if (p->left) { curr->next = p->left; curr = p->left; } if (p->right) { curr->next = p->right; curr = p->right; } } connect(root->right); connect(root->left); } };
|
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
|
class Solution { public: void connect(TreeLinkNode *root) { if (!root) return; if (root->left) { if (root->right) { root->left->next = root->right; } else { root->left->next = next(root->next); } } if (root->right) { root->right->next = next(root->next); } connect(root->right); connect(root->left); }
TreeLinkNode *next(TreeLinkNode *root) { while (root) { if (root->left) return root->left; if (root->right) return root->right; root = root->next; } return nullptr; } };
|