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

本题如果使用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;
    }
};
相关推荐
土司大王43 分钟前
LeetCode hot100——74.搜索二维矩阵:Java 二分模板
java·算法·leetcode
BizzZ_1 小时前
算法(1)——双指针
数据结构
Doubbbbbbble云1 小时前
内存碎片化对数据结构操作性能的影响研究4
数据结构
xiangyun613 小时前
【408数据结构 03】线性表与顺序表:C++手写SeqList
开发语言·数据结构·c++
爱吃苹果的日记本4 小时前
数据结构第三课补充(空间复杂度)
数据结构·学习
不会就选b4 小时前
算法日常・每日刷题--贪心<11>
算法·leetcode·职场和发展
多弗朗皮卡丘4 小时前
数据结构6:队列
c语言·数据结构
xxxiugou1234 小时前
双指针解题秘籍:从入门到精通
c语言·数据结构·c++·算法
Logic1015 小时前
C语言/数据结构位运算题解:异或XOR找出地铁规划中的“独特坐标“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
沉淀的.晴天5 小时前
FreeRTOS信号量
数据结构·算法