Files
LeetCode-Go/leetcode/0129.Sum-Root-to-Leaf-Numbers/129. Sum Root to Leaf Numbers.go
2020-08-07 17:06:53 +08:00

50 lines
934 B
Go

package leetcode
import (
"strconv"
)
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
res, nums := 0, binaryTreeNums(root)
for _, n := range nums {
num, _ := strconv.Atoi(n)
res += num
}
return res
}
func binaryTreeNums(root *TreeNode) []string {
if root == nil {
return []string{}
}
res := []string{}
if root.Left == nil && root.Right == nil {
return []string{strconv.Itoa(root.Val)}
}
tmpLeft := binaryTreeNums(root.Left)
for i := 0; i < len(tmpLeft); i++ {
res = append(res, strconv.Itoa(root.Val)+tmpLeft[i])
}
tmpRight := binaryTreeNums(root.Right)
for i := 0; i < len(tmpRight); i++ {
res = append(res, strconv.Itoa(root.Val)+tmpRight[i])
}
return res
}