LeetCode 129. Sum Root to Leaf Numbers - 二叉树系列题22

2022/3/2 23:46:47

本文主要是介绍LeetCode 129. Sum Root to Leaf Numbers - 二叉树系列题22,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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.

leaf node is a node with no children.

Example 1:

Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

Input: root = [4,9,0,5,1]
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->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



这篇关于LeetCode 129. Sum Root to Leaf Numbers - 二叉树系列题22的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程