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

本题如果使用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;
    }
};
相关推荐
wefg12 分钟前
【算法】倍增思想(快速幂)
数据结构·c++·算法
Zik----10 分钟前
Leetcode24 —— 两两交换链表中的节点(迭代法)
数据结构·算法·链表
!停25 分钟前
数据结构二叉树—链式结构(下)
数据结构·算法
逆境不可逃33 分钟前
LeetCode 热题 100 之 41.缺失的第一个正数
算法·leetcode·职场和发展
666HZ6661 小时前
数据结构5.0 树与二叉树
数据结构
We་ct2 小时前
LeetCode 173. 二叉搜索树迭代器:BSTIterator类 实现与解析
前端·算法·leetcode·typescript
Zik----2 小时前
Leetcode27 —— 移除元素(双指针)
数据结构·算法
踩坑记录3 小时前
leetcode hot100 79. 单词搜索 medium 递归回溯
leetcode
睡一觉就好了。3 小时前
list容器简介及其接口函数
数据结构·list
adore.9683 小时前
2.22 oj基础92 93 94+U12
数据结构·c++·算法