Sum Root to Leaf Numbers - LeetCode 129

题目描述:
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.

分析:
此题其实是考察二叉树的深度优先遍历。要将根节点到每一个叶子节点的路径所得到的整数相加,那么用递归思路实现起来比用迭代简单很多。
递归思路:

每次处理一个节点时都是在该节点之前遍历的节点所构成的整数的基础上。如果当前节点为空,直接返回;如果当前的节点不为空但是左右节点均为空(即当前节点为叶子节点),那么将该节点加入到整数的构成,就完成了一条路径的搜索,将该条路径组成的整数累加到全局和中,然后递归处理它的左右孩子节点即可。

/**///0ms*/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
/**
 * befSum 是处理node之前的该条路径所组成的整数
 * res 是所求
 * node 是当前即将要处理的节点
 */
    void getSum(TreeNode *node, int befNum,int &res){
        if(node == NULL)
            return;
        int curNum = befNum*10 + node->val;
        if(!node->left && !node->right){ //node为叶子节点,将该条路径的整数累加到res中
            res += curNum;
            return;
        }
        getSum(node->left,curNum,res); //递归处理左右孩子节点,将和累加到res中
        getSum(node->right,curNum,res);
    }

    int sumNumbers(TreeNode* root) {
        int res = 0;
        if(root == NULL)
            return res;
        getSum(root,0,res);
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值