type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
//解题思路,用层序遍历即可
func findBottomLeftValue(root *TreeNode) int {
curList := []*TreeNode{root}
if root == nil {
return 0
}
//用切片模拟队列存放当前层节点
res := []int{}
for len(curList) > 0 {
//生成下一层
nextList := []*TreeNode{}
vals := []int{}
for _, v := range curList {
//收集当前层数值
vals = append(vals, v.Val)
if v.Left != nil {
nextList = append(nextList, v.Left)
}
if v.Right != nil {
nextList = append(nextList, v.Right)
}
}
//将下一层变成当前层
curList = nextList
res = vals
}
return res[0]
}
//解题思路,targetSum层层递减,当到叶子节点时,targetSum等于0说找到了相关路径,返回true否则返回false
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
targetSum = targetSum - root.Val
if root.Left == nil && root.Right == nil {
if targetSum == 0 {
return true
}
return false
}
if root.Left != nil {
if hasPathSum(root.Left, targetSum) {
return true
}
}
if root.Right != nil {
if hasPathSum(root.Right, targetSum) {
return true
}
}
return false
}