leetcode update

This commit is contained in:
gameloader 2024-04-15 10:44:20 +08:00
parent ebb9a99102
commit b862dcbe08

View File

@ -3400,3 +3400,57 @@ func leftfirst(root *TreeNode)int{
return sum
}
```
## day48 2024-04-15
### 129. Sum Root to Leaf Numbers
You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
![0415uBAU0k9lKRbE](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/0415uBAU0k9lKRbE.png)
### 题解
仍然使用递归求解, 对树执行后序遍历, 在对子节点调用递归函数时将当前路径到该子节点的父节点组成的数字作为递归函数的参数, 子节点将该参数乘10后传给子节点的子节点, 并将子节点的两个子节点的返回值加和作为路径和返回给父节点. 若该子节点为叶子节点, 则加上叶子节点的值并返回. 最终在根节点将左右两子节点的返回值加和即可得到最终解.
### 代码
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
result := lastnode(root, 0)
return result
}
func lastnode(root *TreeNode, value int) int{
sum := 0
if root.Left != nil{
sum += lastnode(root.Left, value*10+root.Val)
}
if root.Right != nil{
sum += lastnode(root.Right, value*10+root.Val)
}
if root.Left == nil && root.Right == nil{
return value*10+root.Val
}
return sum
}
```
### 总结
运行时间2ms本以为算法效率不够高, 结果看了看运行时间0ms的代码, 代码逻辑和我一模一样, 可能被优化的点在于递归函数中可以先判断是否为叶子节点, 再去创建sum变量. 其实这种将属性传递给子节点的方法在编译原理中的语义分析阶段很常用, 也就是属性文法, 可以看作一种继承属性, 更加详细的内容可以查阅编译原理相关的书籍.