ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-03-02 22:59:38  阅读:167  来源: 互联网

标签:node represents leaf 22 number 二叉树 Leaf root 节点


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

标签:node,represents,leaf,22,number,二叉树,Leaf,root,节点
来源: https://blog.csdn.net/hgq522/article/details/123242242

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有