题目来源:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
解题思路原文:本次展示算法思路来源于题目评论
解题思路作者:https://leetcode-cn.com/u/buringdroplets/
题目
填充每个节点的下一个右侧节点指针
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
class Node { public int val; public Node left; public Node right; public Node next; };
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例
输入:root = [1,2,3,4,5,6,7]
输出:[1,#,2,3,#,4,5,6,7,#]
提示
① 树中节点的数量少于 4096
② -1000 <= node.val <= 1000
解题思路
算法分析过程,由于题目已明确:**初始状态下,所有 next 指针都被设置为 NULL。**所以我们无需考虑 1、3、7节点以及所有与1(最顶部节点)、3、7位置相同的节点。
class Solution {
public Node connect(Node root) {
//避免 4.left 这种不存在的节点
if (root == null)
return null;
//判断是否存在左子叶 比如 4 就没有左子叶
if (root.left != null) {
//2有左子叶4,所以让2的左子叶4连接到2的右子叶5
root.left.next = root.right;
//判断自身是否有next
if (root.next != null)
//如果自己有next,比如2的next是3,那么就让5连接到6
root.right.next = root.next.left;
}
//反复执行所有左子叶
connect(root.left);
//反复执行所有右子叶
connect(root.right);
return root;
}
}
代码清爽版
class Solution {
public Node connect(Node root) {
if (root == null)
return null;
if (root.left != null) {
root.left.next = root.right;
if (root.next != null)
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
return root;
}
}
执行用时:0 ms, 在所有 Java 提交中击败了 100%的用户
内存消耗:38.5 MB, 在所有 Java 提交中击败了 79.15%的用户