[LeetCode]117. 填充每个节点的下一个右侧节点指针 II(java实现)

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 读题(需要重点注意的东西)

思路():
本题与[LeetCode]116. 填充每个节点的下一个右侧节点指针(java实现)的不同之处在于,本题给出的二叉树不一定是一颗完美二叉树。

我们需要在每一层用两个指针维护当前层的链表信息
在这里插入图片描述

具体思路如下:

  1. 用head指向第二层的第一个节点,tail指向第二层的最后一个节点,遍历根节点,依次将根节点的左右儿子插入下一层链表,即 2 - > 3 ;

  2. 用head指向第三层的第一个节点,tail指向第三层的最后一个节点,从左到右遍历第二层依次将第二层的的子节点插入下一层链表,即 4 -> 5 -> 7

  3. 按上述方法,遍历到叶节点层,算法结束

3. 解法

---------------------------------------------------解法---------------------------------------------------

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        Node dummy = root;
        while(root != null){
            // 用head.next存储下一层的头结点
            // 虚拟头结点head
            Node head = new Node(0);
            Node tail = head;
            // 遍历当前层,维护下一层的链表
            for(Node p = root; p != null;p = p.next){
                if(p.left != null){
                    tail.next = p.left;
                    tail = tail.next;
                }
                if(p.right != null){
                    tail.next = p.right;
                    tail = tail.next;
                }
            }
            root = head.next;
        }
        return dummy;
    }
}

可能存在的问题:

4. 可能有帮助的前置习题

5. 所用到的数据结构与算法思想

6. 总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cloudeeeee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值