LeetCode 116. Populating Next Right Pointers in Each Node

LeetCode 116. Populating Next Right Pointers in Each Node (填充每个节点的下一个右侧节点指针)

题目

链接

https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/

问题描述

给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

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

示例

输入:root = [1,2,3,4,5,6,7]
输出:[1,#, 2,3,#,4,5,6,7,#]

提示

树中节点的数量在 [0, 212 - 1] 范围内
-1000 <= node.val <= 1000

思路

同样是树的基本操作,需要注意的就是next初始就是null,最右侧不需要考虑。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(n)

代码

Java

    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        connectNode(root.left,root.right);
        return root;
    }

    public void connectNode(Node n1, Node n2) {
        if (n1 == null || n2 == null) {
            return;
        }
        n1.next = n2;
        connectNode(n1.left, n1.right);
        connectNode(n1.right, n2.left);
        connectNode(n2.left, n2.right);
    }
posted @ 2022-04-09 10:43  cheng102e  阅读(15)  评论(0编辑  收藏  举报