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

本题如果使用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;
    }
};
相关推荐
TracyCoder1234 分钟前
LeetCode Hot100(51/100)——155. 最小栈
数据结构·算法·leetcode
Y.O.U..14 分钟前
力扣刷题-86.分隔链表
算法·leetcode·链表
TracyCoder12335 分钟前
LeetCode Hot100(52/100)——394. 字符串解码
算法·leetcode·职场和发展
thginWalker1 小时前
leetcode有空可以挑战的题目
leetcode
52Hz1181 小时前
力扣207.课程表、208.实现Trie(前缀树)
python·leetcode
shentuyu木木木(森)1 小时前
单调队列 & 单调栈
数据结构·c++·算法·单调栈·单调队列
熬了夜的程序员1 小时前
【LeetCode】119. 杨辉三角 II
算法·leetcode·职场和发展
菜鸡儿齐2 小时前
leetcode-最长连续序列
数据结构·算法·leetcode
Tisfy2 小时前
LeetCode 3713.最长的平衡子串 I:计数(模拟)
算法·leetcode·题解·模拟
熬了夜的程序员2 小时前
【LeetCode】117. 填充每个节点的下一个右侧节点指针 II
java·算法·leetcode