题解 | #左叶子之和#
左叶子之和
https://www.nowcoder.com/practice/405a9033800b403ba8b7b905bab0463d
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
func isLeaf(root *TreeNode) bool {
if root.Left == nil && root.Right == nil {
return true
}
return false
}
func sumOfLeftLeaves( root *TreeNode ) (ans int) {
// write code here
if root == nil {
return
}
q := [1010]*TreeNode{}
hh, tt := 0, 0
q[tt] = root
tt++
for tt > hh {
p := q[hh]
hh++
if p.Left != nil {
if isLeaf(p.Left) {
// fmt.Println(p.Left.Val)
ans = ans + p.Left.Val
} else {
q[tt] = p.Left
tt++
}
}
if p.Right != nil && !isLeaf(p.Right){
q[tt] = p.Right
tt++
}
}
return
}
用切片太慢了, 数组模拟就过了