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

本题如果使用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;
    }
};
相关推荐
blackicexs22 分钟前
第六周第一天
数据结构·算法
52Hz11825 分钟前
力扣20.有效的括号、155.最小栈
python·算法·leetcode
菜鸡儿齐1 小时前
leetcode-电话号码的字母组合
算法·leetcode·职场和发展
We་ct1 小时前
LeetCode 236. 二叉树的最近公共祖先:两种解法详解(递归+迭代)
前端·数据结构·算法·leetcode·typescript
小白菜又菜1 小时前
Leetcode 229. Majority Element II
算法·leetcode·职场和发展
Frostnova丶2 小时前
LeetCode 1461. 检查一个字符串是否包含所有长度为 K 的二进制子串
算法·leetcode·哈希算法
历程里程碑2 小时前
普通数组---合并区间
java·大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎
无忧.芙桃2 小时前
AVL树的实现
数据结构·c++
小白菜又菜3 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见4043 小时前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode