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

本题如果使用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 小时前
跳表(Skip List):简单高效的有序数据结构
数据结构
xlp666hub7 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
xlp666hub10 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
任沫1 天前
字符串
数据结构·后端
祈安_1 天前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法
NineData3 天前
数据库管理工具NineData,一年进化成为数万+开发者的首选数据库工具?
运维·数据结构·数据库
琢磨先生David11 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_4542450311 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝11 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode