层次遍历
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
| class Solution { public: Node* connect(Node* root) { queue<Node*> q; if(root) q.push(root); Node* pre = nullptr; while(q.size()) { int sz = q.size(); for(int i = 0; i < sz; ++i) { Node* node = q.front(); q.pop(); if(node->left) { q.push(node->left); } if(node->right) { q.push(node->right); } if(!pre) { pre = node; } else { pre->next = node; pre = node; } } pre = nullptr; } return root; } };
|
Accepted
55/55 cases passed (8 ms)
Your runtime beats 99.5 % of cpp submissions
Your memory usage beats 34.56 % of cpp submissions (20.1 MB)
递归
重点在于:需要从右边往左边递归。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: Node* connect(Node* root) { if(root && (root->left || root->right)) { if(root->left && root->right) root->left->next = root->right; Node* node = root->right ? root->right : root->left; Node* head = root->next; while(head && !head->left && !head->right) { head = head->next; }
node->next = !head ? nullptr : head->left ? head->left : head->right;
connect(root->right); connect(root->left); } return root; } };
|
Accepted
55/55 cases passed (16 ms)
Your runtime beats 85.93 % of cpp submissions
Your memory usage beats 35.68 % of cpp submissions (20 MB)