填充每个节点的下一个右侧节点Ⅱ-力扣

本题如果使用BFS去层序遍历,代码和 填充每个节点的下一个右侧节点 题没有任何区别。但是使用已经建立好的next链表去做,则需要考虑到next指向的节点子节点是否为空的可能。

cpp 复制代码
class Solution {
public:
    Node* connect(Node* root) {
        if(root == nullptr){
            return nullptr;
        }
        Node * head = root;
        while(head != nullptr){
            Node * dummy = new Node(0);
            Node * temp = dummy;
            
            for(Node* cur = head; cur != nullptr; cur = cur->next){
                if(cur->left != nullptr){
                    temp->next =cur->left;
                    temp = temp->next;
                }
                if(cur->right != nullptr){
                    temp->next = cur->right;
                    temp = temp->next;
                }
            }
            head = dummy->next;
        }

        return root;
    }
};

使用DFS来解决,通过一个数组来记录每一层的前节点,然后不断更新这个数组。

cpp 复制代码
class Solution {
public:
    void dfs(Node* root, vector<Node*>& vec, int depth){
        if(root == nullptr){
            return;
        }
        if(depth >= vec.size()){
            vec.push_back(nullptr);
        }
        if(vec[depth] != nullptr){
            vec[depth]->next = root;
        }
        vec[depth] = root;
        dfs(root->left, vec, depth + 1);
        dfs(root->right, vec, depth + 1);
    }

    Node* connect(Node* root) {
        vector<Node*> vec;
        int depth = 0;
        dfs(root, vec, depth);
        return root;
    }
};
相关推荐
纪念 2293 分钟前
顺序表(数据结构入门的开端)
数据结构
sheeta199811 分钟前
LeetCode 每日一题笔记 日期:2026.05.24 题目:1340. 跳跃游戏 V
笔记·leetcode·游戏
汉字萌萌哒12 分钟前
2025 CSP-S提高级(第一轮)C++真题以及答案
数据结构·算法
z2005093023 分钟前
今日算法(组合问题III)(回溯的使用)
java·算法·leetcode
春栀怡铃声24 分钟前
【C++修仙录02】筑基篇:list 使用
数据结构·list
夏日听雨眠1 小时前
数据结构(BF算法 )
数据结构·算法·排序算法
夏日听雨眠1 小时前
数据结构(KMP算法)
数据结构·算法
并不喜欢吃鱼1 小时前
从零开始 C++----十【C++ 数据结构】AVL 树详解:从原理到实现
开发语言·数据结构·c++
图码1 小时前
[特殊字符] 高效统计排序数组中目标元素的出现次数
数据结构·算法·排序算法·柔性数组·图搜索
炘爚1 小时前
数据结构:单链表
数据结构