# LeetCode题解——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.

SUM(p->val*pow(10,di) ; di为每个叶子节点i到当前节点p的长度，这样当前节点p到叶结点的值就可以求出来了：

sump = SUM(p->val*pow(10,di) + sumleft + sumright

/**
* 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) {
vector<int> d;
return sumNumbers(root,d);
}
int sumNumbers(TreeNode* root, vector<int> & d){
if(!root){
d.push_back(0);
return 0;
}
vector<int> d1,d2;
int s = 0;
if(!root->left && !root->right)  {d.push_back(0);return root->val;}
if(root->left)  s += sumNumbers(root->left,d1);
if(root->right) s += sumNumbers(root->right,d2);
for(auto j:d1){
d.push_back(j+1);
}
for(auto j:d2){
d.push_back(j+1);
}
for(auto i:d){
s+=root->val*pow(10,i);
}
return s;
}
};

#### LeetCode(129)SumRoottoLeafNumbers

2014-02-28 15:57:49

#### Sum Root to Leaf Numbers -- LeetCode

2014-04-04 09:20:44

#### leetcode Sum Root to Leaf Numbers 详细思考分析过程

2013-11-03 09:15:06

#### 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers（所有根到叶子结点组组成的数字相加）】

2015-08-15 06:11:18

#### LeetCode 129:Sum Root to Leaf Numbers

2015-12-31 14:30:09

#### leetcode 129. Sum Root to Leaf Numbers 一个简单的DFS做法 + 注意递归结束条件

2017-09-16 12:41:46

#### Sum Root to Leaf Numbers -- leetcode

2015-05-24 08:49:26

#### [LeetCode 129] Sum Root to Leaf Numbers

2015-03-22 22:36:33

#### LeetCode 129 Sum Root to Leaf Numbers（递归求和）

2017-07-12 20:04:54