forked from daizhenyang/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulating Next Right Pointers in Each Node.cpp
More file actions
47 lines (47 loc) · 1.18 KB
/
Populating Next Right Pointers in Each Node.cpp
File metadata and controls
47 lines (47 loc) · 1.18 KB
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
/**
* 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)return;
queue<TreeLinkNode *>q;
q.push(root);
int node_in_now_level=1;
int node_in_next_level=0;
TreeLinkNode *last=NULL;
while (!q.empty())
{
TreeLinkNode *t=q.front();
q.pop();
if (last)last->next=t;
node_in_now_level--;
if (t->left)
{
node_in_next_level++;
q.push(t->left);
}
if (t->right)
{
node_in_next_level++;
q.push(t->right);
}
if (!node_in_now_level)
{
last=NULL;
swap(node_in_now_level,node_in_next_level);
}
else
{
last=t;
}
}
}
};