From b83cc1602a91c6d9ad3268904d17be42415d6938 Mon Sep 17 00:00:00 2001 From: ironartisan <54694467+ironartisan@users.noreply.github.com> Date: Sun, 5 Sep 2021 10:27:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00404.=E5=B7=A6=E5=8F=B6?= =?UTF-8?q?=E5=AD=90=E4=B9=8B=E5=92=8C.md=E5=B1=82=E5=BA=8F=E8=BF=AD?= =?UTF-8?q?=E4=BB=A3=E8=A7=A3=E6=B3=95Java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 2b627b6c..c0eb7c8e 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -201,7 +201,31 @@ class Solution { } } ``` - +```java +// 层序遍历迭代法 +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + int sum = 0; + if (root == null) return 0; + Queue queue = new LinkedList<>(); + queue.offer(root); + while (!queue.isEmpty()) { + int size = queue.size(); + while (size -- > 0) { + TreeNode node = queue.poll(); + if (node.left != null) { // 左节点不为空 + queue.offer(node.left); + if (node.left.left == null && node.left.right == null){ // 左叶子节点 + sum += node.left.val; + } + } + if (node.right != null) queue.offer(node.right); + } + } + return sum; + } +} +``` ## Python