-
Notifications
You must be signed in to change notification settings - Fork 0
/
0117_Populating_Next_Right_Pointers_In_Each_Node_II.cpp
53 lines (51 loc) · 1.68 KB
/
0117_Populating_Next_Right_Pointers_In_Each_Node_II.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;
// 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) {
TreeLinkNode *head = root; // head of the treeLinklist for next level
TreeLinkNode *prev = NULL; // previous node to connect to current child
TreeLinkNode *cur = NULL; // current node working on
// checking if the is more treeLinkedlist to connect
while (head) {
cur = head; // we are on new level, start connection this level's children
head = NULL;
while (cur) {
// connection left child
if (cur->left) {
if (!prev)
head = cur->left; // next level head
else
prev->next = cur->left;
prev = cur->left;
}
//connection right child
if (cur->right) {
if (!prev)
head = cur->right; // next level head
else
prev->next = cur->right;
prev = cur->right;
}
//Going to the new node of current level
cur = cur->next;
}
prev = NULL;
}
}
};
int main() {
TreeLinkNode *one = new TreeLinkNode(1);
TreeLinkNode *two = new TreeLinkNode(2);
TreeLinkNode *three = new TreeLinkNode(3);
one->left = two;
one->right = three;
Solution t;
t.connect(one);
}