目录

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

本题如果使用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;
    }
};
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
技术小白Byteman24 分钟前
蓝桥刷题note13(排序)
开发语言·数据结构·c++·学习·算法·visualstudio
_星辰大海乀38 分钟前
二叉树相关练习--2
java·开发语言·数据结构·算法·链表·idea
一只拉古39 分钟前
掌握扫描线(sweep line)算法:从LeetCode到现实应用
算法·leetcode·面试
梭七y1 小时前
【力扣hot100题】(064)在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
Dream it possible!1 小时前
LeetCode 热题 100_完全平方数(84_279_中等_C++)(动态规划(完全背包))
c++·leetcode·动态规划·完全背包
Fantasydg1 小时前
DAY 39 leetcode 18--哈希表.四数之和
算法·leetcode·散列表
Protein_zmm2 小时前
[数据结构]图krusakl算法实现
数据结构·算法
勤劳的进取家3 小时前
贪心算法的使用条件
数据结构·python·算法·贪心算法·排序算法·动态规划
南玖yy3 小时前
数据结构C语言练习(设计循环队列)
java·c语言·数据结构
butiehua02023 小时前
Go语言常用算法实现
数据结构·算法·golang·排序算法