116.填充每个节点的下一个右侧节点指针 (Medium)*
题目描述*
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
提示*
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
代码*
如果没有空间限制,那么可以用常规的 bfs 层序遍历,用队列存结点。有空间限制,但正好这是完美二叉树,也可以使用层序遍历,不使用队列。当然可以使用递归。
class Solution {
public:
Node* connect(Node* root) {
queue<Node*> helpQueue;
if(root == nullptr) {
return nullptr;
}
Node *cur = root;
helpQueue.push(cur);
Node *pre = nullptr;
while(!helpQueue.empty()) {
int len = helpQueue.size();
pre = nullptr;
for(int i = 0; i < len; i++) {
cur = helpQueue.front();
helpQueue.pop();
if(i > 0) {
pre->next = cur;
}
pre = cur;
if(cur->left != nullptr) {
helpQueue.push(cur->left);
}
if(cur->right != nullptr) {
helpQueue.push(cur->right);
}
}
}
return root;
}
};
class Solution {
public:
Node* connect(Node* root) {
if(root == nullptr) {
return nullptr;
}
Node *cur = root;
Node *levelRoot = root;
while(levelRoot != nullptr) {
cur = levelRoot;
while(cur != nullptr && cur->left != nullptr) {
cur->left->next = cur->right;
if(cur->next == nullptr) {
cur->right->next = nullptr;
}else {
cur->right->next = cur->next->left;
}
cur = cur->next;
}
levelRoot = levelRoot->left;
}
return root;
}
};
class Solution {
public:
Node* connect(Node* root) {
if(root == nullptr) {
return nullptr;
}
if(root->left != nullptr) {
root->left->next = root->right;
root->right->next = (root->next == nullptr ? nullptr : root->next->left);
connect(root->left);
connect(root->right);
}
return root;
}
};
最后更新: July 23, 2022