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; } };
器
    愿为天下目,萃聚六路华
                    
                
                
            
        
浙公网安备 33010602011771号