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

本题如果使用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;
    }
};
相关推荐
文丑颜不良啊21 分钟前
LeetCode876~900题目解析
java·leetcode
挖井观天5 小时前
《Java数据结构》第一讲:顺序表
数据结构
炘爚6 小时前
数据结构算法总结
数据结构·python·算法
见叶之秋7 小时前
【C++】红与黑的边界:红黑树从插入到自检
数据结构·c++·算法·面试
kiracrimson8 小时前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
木井巳9 小时前
【动态规划: 路径问题】不同路径
java·算法·leetcode·动态规划
CQU_JIAKE9 小时前
10.25【A】
数据结构·算法
晒太羊的猫10 小时前
hot100子串
java·算法·leetcode
海清河晏11111 小时前
加油站问题
数据结构·算法·leetcode
GG.WinGel11 小时前
质数数目(蓝桥杯练习题)
java·数据结构·算法·青少年编程·蓝桥杯