404.左叶子之和增加Go递归精简版

This commit is contained in:
markwang
2024-07-10 10:19:39 +08:00
parent b7eb403ed9
commit 6fd1df5bd7

View File

@ -337,6 +337,21 @@ func sumOfLeftLeaves(root *TreeNode) int {
}
```
**递归精简版**
```go
func sumOfLeftLeaves(root *TreeNode) int {
if root == nil {
return 0
}
leftValue := 0
if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
leftValue = root.Left.Val
}
return leftValue + sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
}
```
**迭代法(前序遍历)**
```go