/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
int sum=0;
int allsum=0;
if(root){
findpath(root,sum,allsum);
}
return allsum;
}
void findpath(TreeNode *root,int sum, int &allsum){
if(root==NULL){
return ;
}
sum=sum*10 + root->val;
if(root->left==NULL && root->right==NULL){
allsum+=sum;
}
if(root->left!=NULL){
findpath(root->left,sum,allsum);
}
if(root->right!=NULL){
findpath(root->right,sum,allsum);
}
}
};
2 根节点到某个值到路径
void ownFindPath(TreeNode * root, int expect, list<TreeNode *> tempPath) { // 发现根节点到某个路径
if (root == NULL) {
return ;
}
tempPath.push_back(root);
if (root->left == NULL && root->right == NULL && root->val == expect) {
res.push_back(tempPath);
}
if (root->left) {
ownFindPath(root->left, expect, tempPath);
}
if (root->right) {
ownFindPath(root->right, expect, tempPath);
}
}