0x00 topic
Give you the root node of a binary root
tree , each node in the tree stores a number between0
to and each path from node to node represents a9
根
叶
数字
For example, the path from 根
node to node represents a number叶
1 -> 2 -> 3
123
Calculate the node generated from the root node to the leaf node. The 所有数字之和
leaf node refers to 没有
the node of the child node
0x01 Ideas
According to the example given in the title: The path
from 根
node to node represents a number. It means that every time you go down a layer, the number of the previous layer must be multiplied and accumulated until the leaf node calculates a path, and then calculates other paths. Until all paths are calculated, the result is obtained叶
1 -> 2 -> 3
123
10
0x02 solution
language:Swift
tree node:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
solution:
func sumNumbers(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
// 最终结果
var res = 0
func sum(_ root: TreeNode?, _val: Int) {
guard let root = root else { return }
// 上一层的结果 乘以 10,加上本节点的值
let out = val * 10 + root.val
// 到了 叶节点
if root.left == nil && root.right == nil {
res += out
return
}
// 去下一层
sum(root.left, out)
sum(root.right, out)
}
//计算
sum(root, 0)
return res
}