算法作业HW12:Leetcode94 Sum Root to Leaf Numbers

Description:

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:

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.



Solution:

  Analysis and Thinking:

题目要求求出输入二叉树的所有路径代表的数字的相加值,其中每一条路径都是根节点到叶节点的,且按顺序组合起来代表一个数字,每一个节点的数字为0-9。可利用递归法实现,因为输出是树的从根到叶的节点的所有路径相加结果,因此,递归条件可设为当前记录的Sum值x10后加上当前遍历的节点的值,然后再把更新的sum传给下一个递归过程。结束条件可设为,若遍历的当前节点为叶子,将目前sum值x10加上叶子值,加到最终结果记录变量当中,最终我们需要把左右子树的和相加。

 

  Steps:

1.判断当前节点是否为空,若是,返回0

2.判断当前节点是否为叶节点,若是,将递归累加和结果x10后加上叶子值,返回

3.如果当前遍历节点为非叶子节点,则遍历其左右子树,并把其左右子树相加,当做最终和值


Codes:

class Solution
{
public:
    int sumNumbers(TreeNode *root)
    {
        return sumNumbers_2(root,0)
    }
    int sumNumbers_2(TreeNode* root,int record)
    {
        if(root==NULL) return 0;//特殊情况,若当前节点为空,返回0
        if(root->right==NULL&&root->left==NULL)  //特殊情况,如果当前值为叶子节点
        {
            return record*10+root->value;
        }
        
        return sumNumbers_2(root->left,record*10+root->value)+sumNumbers_2(root->right,record*10+root->value)  //非叶子节点,将左右子树结果相加
    }
};



Results:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值