From e8978ea6a852d568314488583eca552b1c14bce1 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Sat, 3 Dec 2022 00:41:43 +0800 Subject: [PATCH] =?UTF-8?q?update=200404.=E5=B7=A6=E5=8F=B6=E5=AD=90?= =?UTF-8?q?=E4=B9=8B=E5=92=8C:=20=E4=BF=AE=E6=94=B9=20go=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=EF=BC=8C=E4=BC=98=E5=8C=96=20js=20=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E9=A3=8E=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 83 ++++++++++++++++---------------- 1 file changed, 42 insertions(+), 41 deletions(-) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 6b6fe729..e7ce882c 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -35,7 +35,7 @@ ![图二](https://code-thinking-1253855093.file.myqcloud.com/pics/20220902165805.png) -相信通过这两个图,大家可以最左叶子的定义有明确理解了。 +相信通过这两个图,大家对最左叶子的定义有明确理解了。 那么**判断当前节点是不是左叶子是无法判断的,必须要通过节点的父节点来判断其左孩子是不是左叶子。** @@ -298,48 +298,49 @@ class Solution: ```go func sumOfLeftLeaves(root *TreeNode) int { - var res int - findLeft(root,&res) - return res -} -func findLeft(root *TreeNode,res *int){ - //左节点 - if root.Left!=nil&&root.Left.Left==nil&&root.Left.Right==nil{ - *res=*res+root.Left.Val + if root == nil { + return 0 } - if root.Left!=nil{ - findLeft(root.Left,res) - } - if root.Right!=nil{ - findLeft(root.Right,res) + leftValue := sumOfLeftLeaves(root.Left) // 左 + + if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil { + leftValue = root.Left.Val // 中 } + + rightValue := sumOfLeftLeaves(root.Right) // 右 + + return leftValue + rightValue } ``` -**迭代法** +**迭代法(前序遍历)** ```go func sumOfLeftLeaves(root *TreeNode) int { - var res int - queue:=list.New() - queue.PushBack(root) - for queue.Len()>0{ - length:=queue.Len() - for i:=0;i