forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnect.cpp
30 lines (29 loc) · 1013 Bytes
/
connect.cpp
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
// Time Complexity: O(n)
// Space Complexity: O(1)
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
for(TreeLinkNode *list, *first; root; root = first) { // enumerate each level of depth
list = first = NULL;
for(; root; root = root->next) { // enumerate nodes at the same level of depth
if(!first) first = (root->left)? root->left:root->right;
if(root->left) {
if(list) list->next = root->left;
list = root->left;
}
if(root->right) {
if(list) list->next = root->right;
list = root->right;
}
}
}
}
};