lurenaa的博客

层次遍历

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
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);
q.push(node->right);
}
if(!pre) {
pre = node;
} else {
pre->next = node;
pre = node;
}
}
pre = nullptr;
}
return root;
}
};

Accepted

58/58 cases passed (40 ms)

Your runtime beats 27.01 % of cpp submissions

Your memory usage beats 39.05 % of cpp submissions (19.6 MB)

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
Node* connect(Node* root) {
if(!root)
return root;
helper(root->left, root->right);
return root;
}
void helper(Node* left, Node* right) {
if(!left || !right)
return ;
left->next = right;
helper(left->left, left->right);
helper(left->right, right->left);
helper(right->left, right->right);
}
};

Accepted

58/58 cases passed (36 ms)

Your runtime beats 32.24 % of cpp submissions

Your memory usage beats 63.08 % of cpp submissions (19.3 MB)