-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulating_Next_Right_Pointers_in_Each_Node.cpp
More file actions
40 lines (38 loc) · 1.21 KB
/
Populating_Next_Right_Pointers_in_Each_Node.cpp
File metadata and controls
40 lines (38 loc) · 1.21 KB
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
/**
* 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) {}
* };
*/
/*
O(N)
*/
class Solution {
public:
void connect1(TreeLinkNode *node)
{
if (node) node->next = NULL;
connectHelper1(node);
}
// BFS
void connectHelper1(TreeLinkNode* node) {
if (!node || !(node->left) || !(node->right)) return;
TreeLinkNode* curr = node;
while (curr) {
if (curr->left) curr->left->next = curr->right;
if (curr->right) curr->right->next = (curr->next) ? curr->next->left : NULL;
curr = curr->next;
}
connectHelper1(node->left);
}
// DFS
void connectHelper2(TreeLinkNode* node) {
if (!node || !(node->left) || !(node->right)) return;
node->left->next = node->right;
node->right->next = (node->next) ? node->next->left: NULL;
connectHelper2(node->left);
connectHelper2(node->right);
}
};