From 60799a2f446b0b54bb6dcf29ef302ecf9dfeb3e6 Mon Sep 17 00:00:00 2001 From: posper Date: Tue, 3 Aug 2021 20:53:53 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E5=B1=82=E5=BA=8F?= =?UTF-8?q?=E9=81=8D=E5=8E=86=20116.=E5=A1=AB=E5=85=85=E6=AF=8F=E4=B8=AA?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B=E4=B8=80=E4=B8=AA=E5=8F=B3?= =?UTF-8?q?=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87=E9=92=88=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) 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/