读书人

leetcode Sum Root to Leaf Numbers(全

发布时间: 2013-09-09 20:31:09 作者: rapoo

leetcode Sum Root to Leaf Numbers(所有路径之和)

转载请注明来自souldak,微博:@evagle

观察题目给的返回值类型是int,可以断定这棵树的高度不会超过10,所以数据量其实是非常小的。那就直接dfs遍历这棵树,然后到叶子节点的时候将值加到最终结果上就OK了。思路非常之简单就不详述了。直接上代码:


class Solution {    public:                 int sumNumbers(TreeNode *root) {            if(root==NULL)                                              return 0;                                   int total = 0;                                              dfs(root,0,total);                                                      return total;                                                              }                        void dfs(TreeNode *root,int sum,int& total){            if(root==NULL)                                                      return;                                             if(root->left==NULL&&root->right==NULL){                                        total += sum*10+root->val;                                                 }else{..                                                                           dfs(root->left,sum*10+root->val,total);                                        dfs(root->right,sum*10+root->val,total);            }                                                                          }                                                    };   


读书人网 >其他相关

热点推荐