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

本题如果使用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;
    }
};
相关推荐
Cx330❀1 小时前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
艾莉丝努力练剑2 小时前
【C语言16天强化训练】从基础入门到进阶:Day 1
c语言·开发语言·数据结构·学习
番薯大佬2 小时前
编程算法实例-冒泡排序
数据结构·算法·排序算法
·白小白2 小时前
力扣(LeetCode) ——100. 相同的树(C语言)
c语言·算法·leetcode
ankleless2 小时前
数据结构(03)——线性表(顺序存储和链式存储)
数据结构·考研·链表·顺序表·线性表
KarrySmile2 小时前
Day8--滑动窗口与双指针--1004. 最大连续1的个数 III,1658. 将 x 减到 0 的最小操作数,3641. 最长半重复子数组
数据结构·算法·双指针·滑动窗口·不定长滑动窗口·最大连续1的个数·最长子数组
墩墩同学3 小时前
【LeetCode题解】LeetCode 74. 搜索二维矩阵
算法·leetcode·二分查找
1白天的黑夜16 小时前
前缀和-560.和为k的子数组-力扣(LeetCode)
c++·leetcode·前缀和
m0_672813776 小时前
Leetcode-3427变长子数组求和
leetcode
崎岖Qiu6 小时前
leetcode100.相同的树(递归练习题)
算法·leetcode·二叉树·力扣·递归