Merge pull request #141 from novahe/fix/129

update 129
This commit is contained in:
halfrost
2021-05-30 09:14:07 +08:00
committed by GitHub
3 changed files with 26 additions and 44 deletions

View File

@ -1,9 +1,5 @@
package leetcode
import (
"strconv"
)
import (
"github.com/halfrost/LeetCode-Go/structures"
)
@ -21,29 +17,20 @@ type TreeNode = structures.TreeNode
*/
func sumNumbers(root *TreeNode) int {
res, nums := 0, binaryTreeNums(root)
for _, n := range nums {
num, _ := strconv.Atoi(n)
res += num
}
res := 0
dfs(root, 0, &res)
return res
}
func binaryTreeNums(root *TreeNode) []string {
func dfs(root *TreeNode, sum int, res *int) {
if root == nil {
return []string{}
return
}
res := []string{}
sum = sum*10 + root.Val
if root.Left == nil && root.Right == nil {
return []string{strconv.Itoa(root.Val)}
*res += sum
return
}
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
dfs(root.Left, sum, res)
dfs(root.Right, sum, res)
}

View File

@ -45,4 +45,4 @@ Find the total sum of all root-to-leaf numbers.
## 解题思路
- 这一题是第 257 题的变形题,第 257 题要求输出每条从根节点到叶子节点的路径,这一题变成了把每一个从根节点到叶子节点的数字都串联起来,再累加每条路径,求出最后的总和。实际做题思路基本没变
- 运用前序遍历的思想,当从根节点出发一直加到叶子节点,每个叶子节点汇总一次。

View File

@ -55,9 +55,12 @@ Find the total sum of all root-to-leaf numbers.
package leetcode
import (
"strconv"
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
@ -66,32 +69,24 @@ import (
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
res, nums := 0, binaryTreeNums(root)
for _, n := range nums {
num, _ := strconv.Atoi(n)
res += num
}
res := 0
dfs(root,0,&res)
return res
}
func binaryTreeNums(root *TreeNode) []string {
if root == nil {
return []string{}
func dfs(root *TreeNode,sum int,res *int) {
if root == nil{
return
}
res := []string{}
if root.Left == nil && root.Right == nil {
return []string{strconv.Itoa(root.Val)}
sum = sum*10 + root.Val
if root.Left == nil && root.Right == nil{
*res += sum
return
}
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
dfs(root.Left,sum,res)
dfs(root.Right,sum,res)
}
```