首页 > 其他 > 详细

LeetCode开心刷题五十六天——昨天写在纸上了,回头拍照传上来129. Sum Root to Leaf Numbers

时间:2019-12-11 17:47:11      阅读:103      评论:0      收藏:0      [点我收藏+]
129. Sum Root to Leaf Numbers
Medium

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: A leaf is a node with no children.

Example:

Input: [1,2,3]
    1
   /   2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

Input: [4,9,0,5,1]
    4
   /   9   0
 / 5   1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
这个大神的代码用了很多新特性C11,导致有的都不知道该从何查起,还好最后只搜索[&]查到了相关的解释
PS:多余说一句,根据大部分搜索引擎的原理和网络及其庞大的数据量,数据一定有只是找不到,所以对关键字的
甄别还是很重要的,每次搜索出来,感觉不是自己想要的。就可以看看是什么影响了我的查找
哪个关键字并进行改正
写代码最重要的是多思考,只有多思才能快,所以写完代码不要着急提交,要自己审查到底写的对不对,养成人形coding机和
人形debug器
这次有三个错误:
1.忘写public了你敢信,这都能忘真的是不带脑子了,该打(报错说函数是私有的我还没明白是哪里的问题)
2.std::function也是一句话,后面应该带;
3.函数为void 但是我返回了值,因为这里是直接引用传递的所以不需要返回,值已经发生了改变
auto lamda函数,function方法。都是十分新鲜的知识点对于lambda,[&]符号的意思下面的网址有具体解释
https://www.runoob.com/cplusplus/cpp-functions.html
class Solution{
public:
  int sumNumbers(TreeNode* root)
  {
      int ans=0;
      function<void(TreeNode*,int)> traverse=[&](TreeNode* t,int num)
      {
          if(!t) return;
          num=num*10+t->val;
          if(t->left||t->right)
          {
              traverse(t->left,num);
              traverse(t->right,num);
          }
          else
              ans+=num;
      };
      traverse(root,0);
      return ans;
  }
};

 





LeetCode开心刷题五十六天——昨天写在纸上了,回头拍照传上来129. Sum Root to Leaf Numbers

原文:https://www.cnblogs.com/Marigolci/p/12023952.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!