给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
提示:
树中的节点数小于 6000
-100 <= node.val <= 100
解析:116题的迭代法可以直接套用。
递归的话,寻找next的过程太繁琐,因为存在大量的nullptr可能性,因此列出来仅供参考。
另外这一题迭代法平均用时60ms,而递归法平均用时500ms,导致整个用时柱状图呈现怪异的形状。。。
//迭代法
class Solution {
public:
Node* connect(Node* root){
if(!root) return root;
queue<Node*> q;
q.push(root);
q.push(nullptr);
Node* pre = nullptr;
while(!q.empty()){
auto cur = q.front();
q.pop();
if(cur){
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
if(pre) pre->next = cur;
pre = cur;
}
else{
if(!q.empty())
q.push(nullptr);
pre = nullptr;
}
}
return root;
}
};
//递归法
class Solution {
public:
Node* findnext(Node* root)
{
if(root->next==NULL)
return NULL;
while(root->next!=NULL)
{
if(root->next->left!=NULL)
return root->next->left;
if(root->next->right!=NULL)
return root->next->right;
root=root->next;
}
return NULL;
}
Node* connect(Node* root) {
if(root==NULL)
return root;
if(root->left!=NULL)
{
if(root->right!=NULL)
root->left->next=root->right;
else
root->left->next=findnext(root);
}
if(root->right!=NULL)
{
root->right->next=findnext(root);
}
connect(root->right);
connect(root->left);
return root;
}
};