给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例:
输入:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
输出:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":null,"right":null,"val":7},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"6","left":null,"next":null,"right":{"$ref":"5"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1}
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
提示:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
一、思路
(一)层序遍历法
和之前的一样:LeetCode116-填充每个节点的下一个右侧节点指针
C++代码:
class Solution {
public:
Node* connect(Node* root) {
// 使用层序遍历
if (!root)
return NULL;
queue<Node*> list1, list2;
Node *temp1, *temp2;
list1.push(root);
while (!list1.empty() || !list2.empty()) {
while (!list1.empty()) {
temp1 = list1.front();
list1.pop();
if (list1.empty())
temp1->next = NULL;
else {
temp2 = list1.front();
temp1->next = temp2;
}
if (temp1->left)
list2.push(temp1->left);
if (temp1->right)
list2.push(temp1->right);
}
while (!list2.empty()) {
temp1 = list2.front();
list2.pop();
if (list2.empty())
temp1->next = NULL;
else {
temp2 = list2.front();
temp1->next = temp2;
}
if (temp1->left)
list1.push(temp1->left);
if (temp1->right)
list1.push(temp1->right);
}
}
return root;
}
};