/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int sumNumbers(TreeNode* root) {
// write code here
return dfs(root, 0);
}
//该递归函数的含义为
//返回以root为根节点的二叉树所有路径和,其中pre是root的父节点的权值
int dfs(TreeNode*root,int pre)
{
if(root==NULL)
return 0;
int sum=pre*10+root->val;
if(root->left==NULL&&root->right==NULL)
return sum;
else return dfs(root->left, sum)+dfs(root->right, sum);
}
};
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int sumNumbers(TreeNode* root) {
// write code here
return dfs(root, 0);
}
//该递归函数的含义为
//返回以root为根节点的二叉树所有路径和,其中pre是root的父节点的权值
int dfs(TreeNode*root,int pre)
{
if(root==NULL)
return 0;
int sum=pre*10+root->val;
if(root->left==NULL&&root->right==NULL)
return sum;
else return dfs(root->left, sum)+dfs(root->right, sum);
}
};