Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
中序遍历二叉树,每个经过的节点记录在path中,其中没词遍历到叶节点时,把path中所有值与ans累加即为所求。
dfs(TreeNode* root, int &ans,vector<int>&path)
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
if (root==NULL)
return 0;
vector<int>path;
int ans=0;
dfs(root,ans,path);
return ans;
}
void dfs(TreeNode* root, int &ans,vector<int>&path)
{
if (root==NULL)
{
int temp=0;
for (int i=0; i<path.size(); i++)
{
temp*=10;
temp+=path[i];
}
ans+=temp;
return ;
}
path.push_back(root->val);
if (root->left==NULL&&root->right==NULL)
{
dfs(root->left,ans,path);
}
if (root->left!=NULL)
{
dfs(root->left,ans,path);
}
if (root->right!=NULL)
{
dfs(root->right,ans,path);
}
path.pop_back();
return ;
}
};