Skip to content

Commit 362467d

Browse files
committed
Update Populating_Next_Right_Pointers_in_Each_Node_II.cc
Add non-recursive method.
1 parent bfe84db commit 362467d

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

Populating_Next_Right_Pointers_in_Each_Node_II.cc

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,36 @@ class Solution {
3535
}
3636
connect(nxtLevel);
3737
}
38-
};
38+
};
39+
40+
41+
42+
//Add non-recursive method.
43+
class Solution {
44+
public:
45+
void connect(TreeLinkNode *root) {
46+
// Start typing your C/C++ solution below
47+
// DO NOT write int main() function
48+
TreeLinkNode *pCur = root, *pBegin = NULL;
49+
TreeLinkNode **pTail = &pBegin;
50+
while (pCur != NULL) {
51+
while (pCur != NULL) {
52+
if (pCur->left) {
53+
if (!pBegin) pBegin = pCur->left;
54+
else *pTail = pCur->left;
55+
pTail = &((*pTail)->next);
56+
}
57+
if (pCur->right) {
58+
if (!pBegin) pBegin = pCur->right;
59+
else *pTail = pCur->right;
60+
pTail = &((*pTail)->next);
61+
}
62+
pCur = pCur->next;
63+
}
64+
pCur = pBegin;
65+
pBegin = NULL;
66+
pTail = &pBegin;
67+
}
68+
return;
69+
}
70+
};

0 commit comments

Comments
 (0)