[LeetCode]Sum Root to Leaf Numbers

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.

For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

这个题比较简单,但是深入考察了面试者对于树和递归的理解.
如果你对递归很熟悉的话,那么就会知道这个题可以用树的后序遍历。
一开始我想要不要递归成子问题,后来发现不太可行,比如2+3=5, 那么返回到根10*2+5=25,这样的话你得知道对于这个根节点有多少个子节点,每个节点的深度又不知道。。放弃
后来考虑到用后序遍历:每次递归到叶子(leaf),它的状态是,没有左和右节点。 那么我们记录一个subValue作为参数,告诉我们从上面传下来多少值。
比如说例子的左子树,1->2  那我从上面给的值是1,1*10+2 就可以,再往下走,没了,就返回一个12. 那么再把右子树的值加上,返回,就结束了。
当然,题里给我们一个函数subNumber(TreeNode root) ,是不足以完成递归的,因为我们不知道对于每个递归,上面给的值是多少,我们无法回去。

所以写一个新函数 int subSum(TreeNode cur, int subValue) 用来记录累加到多少了,再用subValue*10+cur.value 就得到了现在的值。如果是叶子了,那就返回,不是再继续往下走。注意我们还得加个判断,如果cur是null,我们要返回0,因为这种情况不是叶子节点,我们要让递归中止。

public class Solution {
    public int sumNumbers(TreeNode root) {
        if(root==null) return 0;
        return subSum(root, 0);
        
    }
    
    public int subSum(TreeNode cur,int subValue){
        if(cur==null) return 0;
        if(cur.left==null && cur.right==null){
            return subValue*10+cur.val;
        }
        int base=10;
        return subSum(cur.left, subValue*base+cur.val)+
        subSum(cur.right, subValue*base+cur.val);
        
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值