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

本题如果使用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;
    }
};
相关推荐
深圳厨神1 分钟前
浅谈数据结构
数据结构
JCBP_2 分钟前
数据结构4
运维·c语言·数据结构·vscode
半桔15 分钟前
红黑树剖析
c语言·开发语言·数据结构·c++·后端·算法
Joe_Wang534 分钟前
[图论]拓扑排序
数据结构·c++·算法·leetcode·图论·拓扑排序
梭七y1 小时前
【力扣hot100题】(033)合并K个升序链表
算法·leetcode·链表
月亮被咬碎成星星1 小时前
LeetCode[383]赎金信
算法·leetcode
嘉友2 小时前
Redis zset数据结构以及时间复杂度总结(源码)
数据结构·数据库·redis·后端
蒙奇D索大2 小时前
【数据结构】图解图论:度、路径、连通性,五大概念一网打尽
数据结构·考研·算法·图论·改行学it
trust Tomorrow4 小时前
每日一题-力扣-2278. 字母在字符串中的百分比 0331
算法·leetcode
姜行运4 小时前
数据结构【链表】
c语言·开发语言·数据结构·链表