题目描述:
给定一个二叉树
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
方法1:
主要思路:
(1)借助队列,实现层次遍历,实现对next指针的赋值;
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
Node* connect(Node* root) {
//处理特殊的情形
if(root==NULL||(root->next==NULL&&root->right==NULL)){
return root;
}
queue<Node*> q;//辅助队列
q.push(root);
Node* cur_node=root;
while(!q.empty()){
int size_layer=q.size();
while(size_layer--){
cur_node=q.front();
q.pop();
if(size_layer){//赋值next
cur_node->next=q.front();
}
//压入下一层的指针
if(cur_node->left){
q.push(cur_node->left);
}
if(cur_node->right){
q.push(cur_node->right);
}
}
}
return root;
}
};
方法2:
主要思路:
(1)利用next指针,已经形成的链表,实现层次的遍历,不再使用队列做辅助;
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
Node* connect(Node* root) {
if(root==NULL||(root->left==NULL&&root->right==NULL)){
return root;
}
Node* cur_head=root;//当前层的头结点
Node* next_head=NULL;//下一层的形成的链表的头结点
while(cur_head){
//用于辅助将下一层的结点连接成链表
Node* cur_node=NULL;
while(cur_head){
//左侧指针
if(cur_head->left!=NULL){
//用于连接下一层的各个结点成为一个链表
if(cur_node==NULL){
cur_node=cur_head->left;
}
else{
cur_node->next=cur_head->left;
cur_node=cur_node->next;
}
//用于获得下一层的链表的头结点
if(next_head==NULL){
next_head=cur_head->left;
}
}
//右侧指针
if(cur_head->right!=NULL){
if(cur_node==NULL){
cur_node=cur_head->right;
}
else{
cur_node->next=cur_head->right;
cur_node=cur_node->next;
}
if(next_head==NULL){
next_head=cur_head->right;
}
}
//更新当前层的结点位置
cur_head=cur_head->next;
}
//跳转到下一层
cur_head=next_head;
next_head=NULL;
}
return root;
}
};