-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path116. Populating Next Right Pointers in Each Node (Leetcode)
82 lines (67 loc) · 1.7 KB
/
116. Populating Next Right Pointers in Each Node (Leetcode)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
Node* getNextPtr(Node* root)
{
Node* temp = root;
temp = temp->next;
while(temp != nullptr)
{
if(temp->left)
return temp->left;
else if(temp->right)
return temp->right;
temp = temp->next;
}
return nullptr;
}
public:
Node* connect(Node* root)
{
if(!root) return nullptr;
Node * temp = root;
root->next = nullptr;
while(temp != nullptr)
{
Node* head = temp;
while(head != nullptr)
{
if(head->left)
{
if(head->right)
{
head->left->next = head->right;
}
else
{
head->left->next = getNextPtr(head);
}
}
if(head->right)
{
head->right->next = getNextPtr(head);
}
head = head->next;
}
if(temp->left)
temp = temp->left;
else if(temp->right)
temp = temp->right;
else
temp = getNextPtr(temp);
}
return root;
}
};