129. Sum Root to Leaf Numbers

题目链接

https://leetcode.com/problems/sum-root-to-leaf-numbers/

代码

class Solution {
public:
    int dfs(TreeNode *pNode, int sum) {
        if (pNode == NULL) {
            return sum;
        }
        int t = sum * 10 + pNode->val;
        if (pNode->right == NULL && pNode->left == NULL) {
            return t;
        }
        int ans = 0;
        if (pNode->left != NULL) {
             ans += dfs(pNode->left, t);
        }
        if (pNode->right != NULL) {
            ans += dfs(pNode->right, t);
        }
        
        return ans;
    }

    int sumNumbers(TreeNode* root) {
        return dfs(root, 0);
    }
};

你可能感兴趣的:(129. Sum Root to Leaf Numbers)