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

本题如果使用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;
    }
};
相关推荐
立志成为大牛的小牛7 分钟前
数据结构——五十四、处理冲突的方法——开放定址法(王道408)
数据结构·学习·程序人生·考研·算法
子一!!7 分钟前
数据结构===红黑树===
数据结构
代码游侠30 分钟前
复习——栈、队列、树、哈希表
linux·数据结构·学习·算法
小白程序员成长日记1 小时前
2025.12.03 力扣每日一题
算法·leetcode·职场和发展
元亓亓亓2 小时前
LeetCode热题100--20. 有效的括号--简单
linux·算法·leetcode
熊猫_豆豆2 小时前
LeetCode 49.字母异位组合 C++解法
数据结构·算法·leetcode
小武~3 小时前
Leetcode 每日一题C 语言版 -- 234 basic calculator
linux·c语言·leetcode
小白程序员成长日记3 小时前
2025.12.02 力扣每日一题
数据结构·算法·leetcode
永远都不秃头的程序员(互关)3 小时前
在vscodeC语言多文件编译实战指南
c语言·数据结构·算法
立志成为大牛的小牛3 小时前
数据结构——五十三、处理冲突的方法——拉链法(王道408)
数据结构·学习·考研·算法