LeetCode OJ-129.Sum Root to Leaf Numbers

LeetCode OJ-129.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.

题目理解

​ 由根节点到最下层的叶节点组成的一条路径表示一个数,如题目中说的,1->2->3,则表示123。题目要求的是二叉树的所有路径代表的数之和,这里可以用简单的先序遍历来处理,每次向字符串中添加该节点表示的数字字符,当遇到最下层的叶节点后,则将字符串转为整型值,做求和。结尾位置要将开头添加的字符删除,做回溯处理。

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

void cal_sum(TreeNode *root, string &nums, int &sum)
{
    if (root == 0) {
        return ;
    }

    nums.push_back('0' + root->val);

    if (root != 0 && root->left == 0 && root->right == 0) {
        sum += stoi(nums);
    }

    cal_sum(root->left, nums, sum);
    cal_sum(root->right, nums, sum);

    nums.pop_back();
    return ;
}

class Solution {
public:
    int sumNumbers(TreeNode* root) {
        int sum = 0;
        string nums;
        cal_sum(root, nums, sum);
        return sum;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值