struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
//recursive to find every path and then sum these path together
void SumRecursive( TreeNode * root, int prev, int& ans )
{
if(root == NULL)
return;
prev = prev*10+root->val;
if (root->left == NULL && root->right == NULL)
{//one path is over
ans += prev;
return;
}
SumRecursive(root->left, prev, ans);
SumRecursive(root->right, prev, ans);
}
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ans = 0;
SumRecursive(root, 0, ans);
return ans;
}
};
second time
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void sumNumbersUtil(TreeNode* root, int curSum, int& totalSum)
{
curSum = curSum*10+root->val;
if(root->left == NULL && root->right == NULL)
{
totalSum += curSum;
return ;
}
if(root->left != NULL) sumNumbersUtil(root->left, curSum, totalSum);
if(root->right != NULL) sumNumbersUtil(root->right, curSum, totalSum);
}
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return 0;
int totalSum = 0;
int curSum = 0;
sumNumbersUtil(root, curSum, totalSum);
return totalSum;
}
};
本文介绍了一种使用递归算法来求解二叉树中所有从根节点到叶子节点的路径数值之和的方法。通过定义`TreeNode`结构体表示二叉树节点,并实现`sumNumbers`函数遍历所有路径,累加每条路径的数值。
269

被折叠的 条评论
为什么被折叠?



