129. 求根到叶子节点数字之和

image.png

深度优先遍历

1深度优先,当节点都为空的时候就是叶子节点了,进行相加处理
2 当非叶子节点时候 采用val =val*10+root.Val 把数字拼接起来

  1. package main
  2. import "fmt"
  3. type TreeNode struct {
  4. Val int
  5. Left *TreeNode
  6. Right *TreeNode
  7. }
  8. func sumNumbers(root *TreeNode) int {
  9. var res int
  10. dfs(root, 0, &res)
  11. return res
  12. }
  13. func dfs(root *TreeNode, val int, res *int) {
  14. if root == nil {
  15. return
  16. }
  17. val = val*10 + root.Val
  18. if root.Left == nil && root.Right == nil {
  19. *res = *res + val
  20. }
  21. dfs(root.Left, val, res)
  22. dfs(root.Right, val, res)
  23. }
  24. func main() {
  25. one := &TreeNode{Val: 1}
  26. two := &TreeNode{Val: 2}
  27. one.Left = two
  28. three := &TreeNode{Val: 3}
  29. one.Right = three
  30. fmt.Println(sumNumbers(one))
  31. four := &TreeNode{Val: 4}
  32. nine := &TreeNode{Val: 9}
  33. four.Left = nine
  34. zero := &TreeNode{Val: 0}
  35. four.Right = zero
  36. five := &TreeNode{Val: 5}
  37. nine.Left = five
  38. one = &TreeNode{Val: 1}
  39. nine.Right = one
  40. fmt.Println(sumNumbers(four))
  41. }

image.png