-
Notifications
You must be signed in to change notification settings - Fork 160
/
Populating_Next_Right_Pointers_in_Each_Node_II.cc
70 lines (67 loc) · 2.02 KB
/
Populating_Next_Right_Pointers_in_Each_Node_II.cc
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
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL)
return;
TreeLinkNode *p = root;
TreeLinkNode *cntNode = NULL;
TreeLinkNode *nxtLevel = NULL;
while (p) {
if (p->left) {
if (cntNode)
cntNode->next = p->left;
cntNode = p->left;
if (nxtLevel == NULL)
nxtLevel = cntNode;
}
if (p->right) {
if (cntNode)
cntNode->next = p->right;
cntNode = p->right;
if (nxtLevel == NULL)
nxtLevel = cntNode;
}
p = p->next;
}
connect(nxtLevel);
}
};
//Add non-recursive method.
class Solution {
public:
void connect(TreeLinkNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeLinkNode *pCur = root, *pBegin = NULL;
TreeLinkNode **pTail = &pBegin;
while (pCur != NULL) {
while (pCur != NULL) {
if (pCur->left) {
if (!pBegin) pBegin = pCur->left;
else *pTail = pCur->left;
pTail = &((*pTail)->next);
}
if (pCur->right) {
if (!pBegin) pBegin = pCur->right;
else *pTail = pCur->right;
pTail = &((*pTail)->next);
}
pCur = pCur->next;
}
pCur = pBegin;
pBegin = NULL;
pTail = &pBegin;
}
return;
}
};