112.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. // type TreeNode struct {
  3. // Val int
  4. // Left *TreeNode
  5. // Right *TreeNode
  6. // }
  7. // important!! "leaf node"
  8. func hasPathSumIter(root *TreeNode, sum int, tmpSum int) bool {
  9. if root.Left == nil && root.Right == nil {
  10. return tmpSum+root.Val == sum
  11. }
  12. if root.Left == nil {
  13. return hasPathSumIter(root.Right, sum, tmpSum+root.Val)
  14. }
  15. if root.Right == nil {
  16. return hasPathSumIter(root.Left, sum, tmpSum+root.Val)
  17. }
  18. return hasPathSumIter(root.Left, sum, tmpSum+root.Val) || hasPathSumIter(root.Right, sum, tmpSum+root.Val)
  19. }
  20. /**
  21. * Definition for a binary tree node.
  22. * type TreeNode struct {
  23. * Val int
  24. * Left *TreeNode
  25. * Right *TreeNode
  26. * }
  27. */
  28. func hasPathSum(root *TreeNode, sum int) bool {
  29. if root == nil {
  30. return false
  31. }
  32. return hasPathSumIter(root, sum, 0)
  33. }
  34. // func main() {
  35. // /**
  36. // * t1: 5
  37. // * / \
  38. // * 1 4
  39. // * / \
  40. // * 2 3
  41. // */
  42. // t1r := TreeNode{4, nil, nil}
  43. // t1 := &TreeNode{5, nil, &t1r}
  44. // fmt.Println(hasPathSum(t1, 11))
  45. // fmt.Println(hasPathSum(t1, 5))
  46. // fmt.Println(hasPathSum(t1, 7))
  47. // fmt.Println(hasPathSum(nil, 0))
  48. // }