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

「这是我参与11月更文挑战的第21天,活动详情查看:2021最后一次更文挑战」。

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

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

1
2
3
4
5
6
7
8
> c复制代码struct Node {
> int val;
> Node *left;
> Node *right;
> Node *next;
> }
>
>

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

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/po…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:层序遍历
  • 首先,如果root为空或者左右子节点都为空,则不需要处理next指针,直接返回root。
  • 否则,当二叉树不只有一个节点时,利用队列对二叉树进行层序遍历记录二叉树每一层的节点,然后按顺序处理当前层每一个节点的next指针。由于处理过程中所有的节点顺序并没有进行改变,所以最后返回root。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
java复制代码import com.kaesar.leetcode.Node;

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

public class LeetCode_116 {
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();
}
}

【每日寄语】 好好学习,天天向上。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%