leetcode 129. Sum Root to Leaf Numbers

https://www.cnblogs.com/grandyang/p/4273700.html

sum代表当前节点的和。

这个题要从上往下的思路去做。

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

 

上一篇:Leetcode-5017 Sum of Root To Leaf Binary Numbers(从根到叶的二进制数之和)


下一篇:有根树的表达 Aizu - ALDS1_7_A: Rooted Trees