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 number123
.
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.
Example 1:
Input: root = [1,2,3] Output: 25 Explanation: The root-to-leaf path1->2
represents the number12
. The root-to-leaf path1->3
represents the number13
. Therefore, sum = 12 + 13 =25
.
Example 2:
Input: root = [4,9,0,5,1] Output: 1026 Explanation: The root-to-leaf path4->9->5
represents the number 495. The root-to-leaf path4->9->1
represents the number 491. The root-to-leaf path4->0
represents the number 40. Therefore, sum = 495 + 491 + 40 =1026
.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. 0 <= Node.val <= 9
- The depth of the tree will not exceed
10
.
有一棵二叉树,每个节点的节点值都是在0~9范围内,从根节点到每个叶节点的路径代表一个数,路径的每个节点值表示这个数从高位到低位的一位。
其实这题跟LeetCode 113. Path Sum II 基本上差不多,区别是一个是把路径上所有节点值加起来,另一个是把路径上所有节点值转换成其表示的一个数。那么该如何转换成一个数呢?其实就是从根节点开始每往下一层当前数值向左移动一位(十进制向左移动一位,即乘以10)再加上当前节点值,假设根节点到一个叶节点的路径为"1->2->3‘’,那么这个数就是((1*10+2)*10+3 = 123。剩下就跟LeetCode 113. Path Sum II 一样,使用前序遍历算法遍历每一条根到叶的路径即可。
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
res = 0
def dfs(node, num):
if not node:
return
nonlocal res
num = num * 10 + node.val
if not node.left and not node.right:
res += num
return
dfs(node.left, num)
dfs(node.right, num)
dfs(root, 0)
return res