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

深度优先遍历
1深度优先,当节点都为空的时候就是叶子节点了,进行相加处理
2 当非叶子节点时候 采用val =val*10+root.Val 把数字拼接起来
package mainimport "fmt"type TreeNode struct {Val intLeft *TreeNodeRight *TreeNode}func sumNumbers(root *TreeNode) int {var res intdfs(root, 0, &res)return res}func dfs(root *TreeNode, val int, res *int) {if root == nil {return}val = val*10 + root.Valif root.Left == nil && root.Right == nil {*res = *res + val}dfs(root.Left, val, res)dfs(root.Right, val, res)}func main() {one := &TreeNode{Val: 1}two := &TreeNode{Val: 2}one.Left = twothree := &TreeNode{Val: 3}one.Right = threefmt.Println(sumNumbers(one))four := &TreeNode{Val: 4}nine := &TreeNode{Val: 9}four.Left = ninezero := &TreeNode{Val: 0}four.Right = zerofive := &TreeNode{Val: 5}nine.Left = fiveone = &TreeNode{Val: 1}nine.Right = onefmt.Println(sumNumbers(four))}

