112.go 1.1 KB

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