-
Notifications
You must be signed in to change notification settings - Fork 0
/
sumOfLeftLeaves.go
51 lines (47 loc) · 944 Bytes
/
sumOfLeftLeaves.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package _021_11
// Sum of Left Leaves
// leetcode: https://leetcode-cn.com/problems/sum-of-left-leaves/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func SumOfLeftLeaves(root *TreeNode) int {
ans := 0
var dfs func(tn *TreeNode, left bool)
dfs = func(tn *TreeNode, left bool) {
if tn == nil {
return
}
if left && tn.Left == nil && tn.Right == nil {
ans += tn.Val
return
}
dfs(tn.Left, true)
dfs(tn.Right, false)
}
dfs(root.Left, true)
dfs(root.Right, false)
return ans
}
func SumOfLeftLeaves2(root *TreeNode) int {
var dfs func(tn *TreeNode) int
dfs = func(tn *TreeNode) int {
ans := 0
if tn.Left != nil {
if IsLeave(tn.Left) {
ans += tn.Left.Val
} else {
ans += dfs(tn.Left)
}
}
if tn.Right != nil && !IsLeave(tn.Right) {
ans += dfs(tn.Right)
}
return ans
}
return dfs(root)
}
func IsLeave(tn *TreeNode) bool {
return tn.Left == nil && tn.Right == nil
}