# [LeetCode] 129. 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.

【解释】 给一颗二叉树，要求返回其从根结点到叶子结点组成数字之和。从根结点到叶子结点从上到下对应从左到右。例如路径1->2，则代表数字为12. 【思路】 基本上和Path Sum II同样的思路，上篇博文也有。思路基本相同，只不过在找到满足条件的子集之后，本题要做的是加和。

```public class Solution {
private int sum=0;
public int getNum(List<Integer> list){//得到所在list所有值的正数表示
int res=0;
for(int i=0;i<list.size();i++){
res=res*10+list.get(i);
}
return res;
}
public void sumNumbersCore(List<Integer> list, TreeNode root){
if(root.left==null&&root.right==null)
sum+=getNum(list);//将所有路径代表的数字累加
else{
if(root.left!=null)
sumNumbersCore(list,root.left);
if(root.right!=null)
sumNumbersCore(list,root.right);
}
list.remove(list.size()-1);
}
public int sumNumbers(TreeNode root) {
if(root==null) return 0;//空树
List<Integer> list=new ArrayList<Integer>();
sumNumbersCore(list,root);
return sum;
}
}```

50 篇文章33 人订阅

0 条评论

## 相关文章

1K0

2752

### ehcache报错

jfinal2.0+tomcat7+ehcache2.6.11+Linux Linux version 2.6.18-164.el5 (mockbuild@x8...

3749

### echarts太阳分布图-饼图来回穿梭

var dom = document.getElementById("container");

1412

### Save Camera Document

#pragma once #include "HCCamera.h" #include <time.h> #include <cstdio> #incl...

2908

972

2798

### Best Bluemix Content

image.png Watson Services for Bluemix Sample Apps: Watson Films App (Video) Wats...

2654