leetcode刷题,总结,记录,备忘 129

这篇博客介绍了LeetCode第129题,即如何计算二叉树中所有根到叶节点路径表示的数字之和。通过递归方法,将路径上的节点值依次加入字符串,到达叶子节点时将字符串转为整数并存储。最后返回路径数组,将所有整数相加,得到总和。博主分享了他们的解题思路和经验,认为这种类型的递归问题变得相对简单。
摘要由CSDN通过智能技术生成

leetcode129Sum 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.

一言以蔽之,请使用递归。分别在先将本层的节点的值域放入string中,然后,当进入最深处的子节点时,将string放入vector。然后在返回自己这层的时候,去掉自己这层节点的值域,以此往复,最后遍历结果数组,atoi转成int型相加即可,具体内容见代码,有问题可以详细探讨。。。我之前写的很多题目中都有类似的递归方式,,,所以我这次很快就有思路,并且迅速的写出来了。现在觉得这类的算法题目真的很简单。。。

/**
 * 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:
    void function(TreeNode * root, vector<string> & str, string & temp)
    {
        
        if (root->left == NULL && root->right == NULL)
        {
            temp += '0' + root->val;
            str.push_back(temp);
            temp = temp.substr(0, temp.size() - 1);
            return ;
        }
        
   
        temp += '0' + root->val;
        if (root->left)
        {
           function(root->left, str, temp);
        }
        if (root->right)
        {
           function(root->right, str, temp);
        }
        temp = temp.substr(0, temp.size() - 1);
        
    }
    
    int sumNumbers(TreeNode* root) {
        if (root == NULL)
        return 0;
        vector<string> str;
        string temp;
        
        function(root, str, temp);
        
        //str.erase(unique(str.begin(), str.end()), str.end());
        
        int sum = 0;
        
        for (vector<string>::iterator it = str.begin(); it != str.end(); ++it)
        {
            sum += atoi((*it).c_str());
        }
        
        return sum;
    }
};

刚没上代码就发布了,,编辑下,补上。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值