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);
            }                                                                  
        }                                                    
};   



posted @ 2013-09-09 20:19  pangbangb  阅读(138)  评论(0编辑  收藏  举报