Skip to content

Commit cb42b05

Browse files
committed
add level.cpp
1 parent c28516c commit cb42b05

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/connect.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(1)
3+
4+
/**
5+
* Definition for binary tree with next pointer.
6+
* struct TreeLinkNode {
7+
* int val;
8+
* TreeLinkNode *left, *right, *next;
9+
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
void connect(TreeLinkNode *root) {
15+
for(TreeLinkNode *list, *first; root; root = first) { // enumerate each level of depth
16+
list = first = NULL;
17+
for(; root; root = root->next) { // enumerate nodes at the same level of depth
18+
if(!first) first = (root->left)? root->left:root->right;
19+
if(root->left) {
20+
if(list) list->next = root->left;
21+
list = root->left;
22+
}
23+
if(root->right) {
24+
if(list) list->next = root->right;
25+
list = root->right;
26+
}
27+
}
28+
}
29+
}
30+
};

0 commit comments

Comments
 (0)