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

本题如果使用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;
    }
};
相关推荐
wdfk_prog1 天前
[Linux]学习笔记系列 -- lib/timerqueue.c Timer Queue Management 高精度定时器的有序数据结构
linux·c语言·数据结构·笔记·单片机·学习·安全
zhuzhuxia⌓‿⌓1 天前
线性表的顺序和链式存储
数据结构·c++·算法
未知陨落1 天前
LeetCode:95.编辑距离
算法·leetcode
高山有多高1 天前
栈:“后进先出” 的艺术,撑起程序世界的底层骨架
c语言·开发语言·数据结构·c++·算法
YouEmbedded1 天前
解码查找算法与哈希表
数据结构·算法·二分查找·散列表·散列查找·线性查找
小秋学嵌入式-不读研版1 天前
C61-结构体数组
c语言·开发语言·数据结构·笔记·算法
Nix Lockhart1 天前
《算法与数据结构》第七章[算法3]:图的最小生成树
c语言·数据结构·算法
名誉寒冰1 天前
【LeetCode】454. 四数相加 II 【分组+哈希表】详解
算法·leetcode·散列表
tao3556671 天前
【Python刷力扣hot100】49. Group Anagrams
开发语言·python·leetcode