leetcode117. 填充每个节点的下一个右侧节点指针 II-medium

LeetCode 117 二叉树节点 next 指针填充

1 题目:填充每个节点的下一个右侧节点指针 II

官方标定难度:中

给定一个二叉树:

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL 。

初始状态下,所有 next 指针都被设置为 NULL 。

示例 1:

在这里插入图片描述

输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),‘#’ 表示每层的末尾。

示例 2:

输入:root = []
输出:[]

提示:

树中的节点数在范围 [0, 6000] 内
-100 <= Node.val <= 100

进阶:

你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序的隐式栈空间不计入额外空间复杂度。

2 solution

采用层序遍历然后填写 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) return root;
    vector<Node *> last = {root};
    vector<Node *> cur;

    while (!last.empty()) {
        for (auto x: last) {
            if (x->left) cur.push_back(x->left);
            if (x->right) cur.push_back(x->right);
        }
        for(int i = 1; i < cur.size(); i++){
            cur[i - 1]->next = cur[i];
        }
        swap(cur, last);
        cur = {};
    }
    return root;
}
};

结果

在这里插入图片描述

3 进阶

根据本层的next关系填写下一层的next关系,只需要记录上一个节点和下一层的开始节点即可。

代码

class Solution {

public:
    Node *connect(Node *root) {
        if (!root) return root;

        // 层序遍历
        Node *s = root; // 本层的开始
        Node *ss = nullptr; // 下一层的开始
        while (s){
            Node *last = nullptr; // 前一个节点
            for(Node *cur = s; cur; cur = cur->next){ // 遍历本层
                if(cur->left){
                    if(last) { // 如果不是第一个
                        last->next = cur->left;
                    }
                    last = cur->left;
                    if(!ss) ss = cur->left;
                }

                if(cur->right){
                    if(last) { // 如果不是第一个
                        last->next = cur->right;
                    }
                    last = cur->right;
                    if(!ss) ss = cur->right;
                }
            }
            s = ss;
            ss = nullptr;
        }

        return root;
    }
};

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智趣代码实验室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值