LeetCode 129. Sum Root to Leaf Numbers 动态演示

树的数值为[0, 9], 每一条从根到叶子的路径都构成一个整数,(根的数字为首位),求所有构成的所有整数的和

深度优先搜索,通过一个参数累加整数

class Solution {
public:    
    void helper(TreeNode* node, int path, int& sum){
        if(!node){
            return;
        }
        //a(node)
        //lk("root",node)
        //a(path)
        //dsp
        if(!node->left && !node->right){
            sum+=path*10+node->val;
            //dsp
            return;
        }
        
        helper(node->left, path*10+node->val, sum);        
        helper(node->right, path*10+node->val, sum);        
    }
    
    int sumNumbers(TreeNode* root) {
        int sum=0;
        //ahd(root)
        //a(sum)
        helper(root, 0, sum);
        return sum;
    }
};

程序运行动态演示:http://simpledsp.com/FS/Html/lc129.html

猜你喜欢

转载自www.cnblogs.com/leetcoder/p/11333870.html
今日推荐