From 659b34c22f171d011ce8b9e3a826954183c30315 Mon Sep 17 00:00:00 2001 From: ironartisan Date: Sat, 4 Sep 2021 15:06:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00222.=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E8=BF=AD=E4=BB=A3=E8=A7=A3=E6=B3=95Java=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0222.完全二叉树的节点个数.md | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 6268c447..13017f7f 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -204,7 +204,27 @@ class Solution { } } ``` - +```java +class Solution { + // 迭代法 + public int countNodes(TreeNode root) { + if (root == null) return 0; + Queue queue = new LinkedList<>(); + queue.offer(root); + int result = 0; + while (!queue.isEmpty()) { + int size = queue.size(); + while (size -- > 0) { + TreeNode cur = queue.poll(); + result++; + if (cur.left != null) queue.offer(cur.left); + if (cur.right != null) queue.offer(cur.right); + } + } + return result; + } +} +``` ```java class Solution { /**