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

本题如果使用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;
    }
};
相关推荐
孑渡40 分钟前
【LeetCode】每日一题:跳跃游戏
python·算法·leetcode·游戏·职场和发展
liulanba42 分钟前
leetcode--二叉树中的最长交错路径
linux·算法·leetcode
Puppet__1 小时前
【康复学习--LeetCode每日一题】3115. 质数的最大距离
学习·算法·leetcode
xw-pp1 小时前
回溯法的小结与概述
java·数据结构·c++·python·算法·递归
每天努力进步!2 小时前
LeetCode热题100刷题6:160. 相交链表、206. 反转链表、234. 回文链表、141. 环形链表、142. 环形链表 II
c++·算法·leetcode·链表
爱编程的Tom2 小时前
Map && Set(Java篇详解)
java·开发语言·数据结构·学习·算法
JokerSZ.3 小时前
【Leetcode 每日一题】268. 丢失的数字
数据结构·算法·leetcode
㣲信团队4 小时前
小和问题和逆序对问题
数据结构·算法
muyierfly4 小时前
DAY19-力扣刷题
数据结构·算法·leetcode
hummhumm4 小时前
数据结构第08小节:双端队列
java·数据结构·spring boot·spring·java-ee·maven·intellij-idea