diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 8be3ac47..7d459ad9 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1254,6 +1254,44 @@ func connect(root *Node) *Node { } ``` +Java 代码: + +```java +// 二叉树之层次遍历 +class Solution { + public Node connect(Node root) { + Queue queue = new LinkedList<>(); + if (root != null) { + queue.add(root); + } + while (!queue.isEmpty()) { + int size = queue.size(); + Node node = null; + Node nodePre = null; + + for (int i = 0; i < size; i++) { + if (i == 0) { + nodePre = queue.poll(); // 取出本层头一个节点 + node = nodePre; + } else { + node = queue.poll(); + nodePre.next = node; // 本层前一个节点 next 指向当前节点 + nodePre = nodePre.next; + } + if (node.left != null) { + queue.add(node.left); + } + if (node.right != null) { + queue.add(node.right); + } + } + nodePre.next = null; // 本层最后一个节点 next 指向 null + } + return root; + } +} +``` + ## 117.填充每个节点的下一个右侧节点指针II 题目地址:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/