-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopulateNextPointer.cpp
58 lines (43 loc) · 1.31 KB
/
populateNextPointer.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
54
55
56
57
58
/**
* 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) {}
* };
*/
void solve(TreeLinkNode* root){
queue<TreeLinkNode*> currentLevel;
queue<TreeLinkNode*> nextLevel;
currentLevel.push(root);
while(!currentLevel.empty()){
TreeLinkNode* temp = currentLevel.front();
currentLevel.pop();
temp->next = NULL;
if(temp){
if(temp->left)
nextLevel.push(temp->left);
if(temp->right)
nextLevel.push(temp->right);
}
while(!currentLevel.empty()){
TreeLinkNode* temp1 = currentLevel.front();
currentLevel.pop();
temp->next = temp1;
temp = temp1;
if(temp){
// cout<<temp->val<<" ";
if(temp->left)
nextLevel.push(temp->left);
if(temp->right)
nextLevel.push(temp->right);
}
}
if(currentLevel.empty()){
swap(currentLevel,nextLevel);
}
}
}
void Solution::connect(TreeLinkNode* A) {
solve(A);
}