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

本题如果使用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;
    }
};
相关推荐
流年如夢3 小时前
单链表Ⅲ(LeetCode)
数据结构·算法·leetcode·职场和发展
洛水水4 小时前
【数据结构】红黑树详解
数据结构·红黑树
炸膛坦客4 小时前
嵌入式 - 数据结构与算法:(1-9)数据结构 - 队列(Queue)
c语言·数据结构
AbandonForce5 小时前
哈希表(HashTable,散列表)个人理解
开发语言·数据结构·c++·散列表
mask哥5 小时前
力扣算法java实现汇总整理(下)
java·算法·leetcode
代码中介商5 小时前
栈结构完全指南:顺序栈实现精讲
c语言·开发语言·数据结构
样例过了就是过了5 小时前
LeetCode热题100 编辑距离
数据结构·c++·算法·leetcode·动态规划
khalil10206 小时前
代码随想录算法训练营Day-46 动态规划13 | 647. 回文子串、516.最长回文子序列、动态规划总结
数据结构·c++·算法·leetcode·动态规划·回文子串·回文子序列
he___H6 小时前
算法快与慢--哈希+双指针
算法·leetcode·哈希算法
richard_yuu7 小时前
数据结构|二叉树层序遍历 & 线索二叉树:吃透二叉树进阶核心考点
数据结构