LeetCode-117-填充每个节点的下一个右侧节点指针 II

填充每个节点的下一个右侧节点指针 II

题目描述:给定一个二叉树:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

初始状态下,所有 next 指针都被设置为 NULL。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:层序遍历

求解过程和 LeetCode-116-填充每个节点的下一个右侧节点指针 这道题完全一样,现在想想,116题中提到完美二叉树,应该使用完美二叉树的一些性质有更优的解法,而当前的解法是通用的二叉树的解法。

  • 首先,如果root为空或者左右子节点都为空,则不需要处理next指针,直接返回root。
  • 否则,当二叉树不只有一个节点时,利用队列对二叉树进行层序遍历记录二叉树每一层的节点,然后按顺序处理当前层每一个节点的next指针。由于处理过程中所有的节点顺序并没有进行改变,所以最后返回root。
import com.kaesar.leetcode.Node;

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode_117 {
    /**
     * 处理方式同 LeetCode-116-填充每个节点的下一个右侧节点指针
     * @param root
     * @return
     */
    public static Node connect(Node root) {
        // 如果root为空或者左右节点都为空,不需要处理,直接返回root
        if (root == null) {
            return root;
        }
        if (root.left == null && root.right == null) {
            return root;
        }
        // 利用队列记录每层的节点
        Queue<Node> nodes = new LinkedList<>();
        nodes.add(root);
        while (!nodes.isEmpty()) {
            int count = nodes.size();
            Node last = nodes.poll();
            if (last.left != null) {
                nodes.add(last.left);
            }
            if (last.right != null) {
                nodes.add(last.right);
            }

            count--;
//             处理每层的节点的next指针
            while (count > 0) {
                Node curNode = nodes.poll();
                if (curNode.left != null) {
                    nodes.add(curNode.left);
                }
                if (curNode.right != null) {
                    nodes.add(curNode.right);
                }
                last.next = curNode;
                last = curNode;
                count--;
            }

        }
        return root;
    }

    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);

        root.print();
        connect(root);
        System.out.println();
        root.print();
    }
}

【每日寄语】 逃避压力是没有用的,只会让压力更嚣张,勇敢地去面对。

posted @   醉舞经阁  阅读(52)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示