sum-root-to-leaf-numbers (前序遍历)

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

猜你喜欢

转载自www.cnblogs.com/ALINGMAOMAO/p/10019036.html