美文网首页
129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

作者: jecyhw | 来源:发表于2019-06-16 10:41 被阅读0次

题目链接

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

      本文链接:https://www.haomeiwen.com/subject/eciwfctx.html