原题链接:Leecode 129. 求根节点到叶节点数字之和
代码一
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> path;
int res=0;
void dfs(TreeNode* root)
{
if(root->left==nullptr && root->right==nullptr)
{
int tmp=0;
for(int i=0;i<path.size();i++)
{
tmp=tmp*10+path[i];
}
res+=tmp;
return ;
}
if(root->left)
{
path.push_back(root->left->val);
dfs(root->left);
path.pop_back();
}
if(root->right)
{
path.push_back(root->right->val);
dfs(root->right);
path.pop_back();
}
}
int sumNumbers(TreeNode* root) {
path.push_back(root->val);
dfs(root);
return res;
}
};
代码二:
class Solution {
public:
int dfs(TreeNode* root,int pre)
{
if(root==nullptr) return 0;
int sum=pre*10+root->val;
if(root->left==nullptr && root->right==nullptr) return sum;
else return dfs(root->left,sum)+dfs(root->right,sum);
}
int sumNumbers(TreeNode* root) {
return dfs(root,0);
}
};