leetcode 129. Sum Root to Leaf Numbers

本文介绍了一种算法,用于解决给定二叉树中,所有从根节点到叶子节点路径所代表数字的总和问题。通过递归方式,每深入一层就将当前数字乘以10加上节点值,直至到达叶子节点返回最终数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]

    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: [4,9,0,5,1]

    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.

给出一个二叉树,每个root到leaf的路径代表一个数字,问所有路径的数字和是多少

思路:
每往下一level走一步,就需要前一数字10 + 正在访问点的val
假设上一层的值是prefix,那么正在访问节点处的值就是prefix
10 + root.val
而且左右子树共用同一个prefix

当已经是leaf时,返回prefix* 10 + root.val即可

//0ms
    public int sumNumbers(TreeNode root) {
        return helper(root, 0);
    }
    
    public int helper(TreeNode root, int prefix) {
        if (root == null) {
            return 0;
        }
        
        int sum = prefix * 10 + root.val;
        
        if (root.left == null && root.right == null) {
            return sum;
        }
        
        return helper(root.left, sum) + helper(root.right, sum);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值