129. Sum Root to Leaf Numbers
2019-06-16 本文已影响0人
jecyhw
题目链接
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);
}
};