Leetcode在线编程 sum-root-to-leaf-numbers

Leetcode在线编程 sum-root-to-leaf-numbers

题目链接

sum-root-to-leaf-numbers

题目描述

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.


题意

以根到每一个叶结点的遍历序列当成一个数,求这些数之和

解题思路

逐层递归,考虑利用第二个函数,单用一个函数实现起来比较麻烦
在另一个函数里设置一个参数cnt代表当前的遍历序列,因为题目要
求返回的是int,所以这里用int来保存遍历序列,不会产生越界问题
cnt要怎么去更新呢
我们可以考虑每次cnt*10再加上当前节点的值就可以了
当根节点为时cnt为0,root->val设置为rv
即root->val + cnt *10
因为前面的序列乘以10再加上该节点的val的话,就是新的遍历序列
以此类推

AC代码

class Solution {
public:
    int dfs(TreeNode *root ,int cnt)
    {
        if(root==NULL)
            return 0;
        if(root->left==NULL && root->right ==NULL)
            return root->val + cnt * 10;
        return dfs(root->left ,root->val + cnt * 10) + dfs(root->right,root->val + cnt * 10);
    }
    int sumNumbers(TreeNode *root) {
        return dfs(root,0);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值