-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path117-填充同一层的兄弟节点 2.cpp
More file actions
61 lines (61 loc) · 1.76 KB
/
117-填充同一层的兄弟节点 2.cpp
File metadata and controls
61 lines (61 loc) · 1.76 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* 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) {
/*
//使用O(n)的空间
if(root == NULL)
return;
queue<TreeLinkNode*> q; //存放同层的兄弟节点
q.push(root);
while(!q.empty())
{
int count = q.size(); //兄弟节点的个数
for(int i=0;i<count;i++)
{
//兄弟依次出队,除了最右端节点外,每个节点的next指针要指向下一个节点
TreeLinkNode* node = q.front();
q.pop();
//将下一层的节点入队,按左右子节点的顺序
if(node->left != NULL)
q.push(node->left);
if(node->right != NULL)
q.push(node->right);
if( i != count - 1)
node->next = q.front();
//else
//node->next = NULL;
}
}
*/
TreeLinkNode* dummy = new TreeLinkNode(0);
TreeLinkNode* pre = dummy;
while(root != NULL)
{
if(root->left != NULL)
{
pre->next = root->left;
pre = pre->next;
}
if(root->right != NULL)
{
pre->next = root->right;
pre = pre->next;
}
root = root->next;
if(root == NULL)
{
root = dummy->next;
pre = dummy;
dummy->next = NULL;
}
}
}
};