给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。
每条从根节点到叶节点的路径都代表一个数字:
例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
计算从根节点到叶节点生成的 所有数字之和 。
叶节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3]
输出:25
解释:
从根到叶子节点路径 1->2 代表数字 12
从根到叶子节点路径 1->3 代表数字 13
因此,数字总和 = 12 + 13 = 25
示例 2:
输入:root = [4,9,0,5,1]
输出:1026
解释:
从根到叶子节点路径 4->9->5 代表数字 495
从根到叶子节点路径 4->9->1 代表数字 491
从根到叶子节点路径 4->0 代表数字 40
因此,数字总和 = 495 + 491 + 40 = 1026
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void dfs(TreeNode root, List<Integer> tmpList, List<List<Integer>> results) {
if (null == root) return;
tmpList.add(root.val);
if (null == root.left && null == root.right) results.add(new ArrayList<Integer>(tmpList));
dfs(root.left, tmpList, results);
dfs(root.right, tmpList, results);
// 回溯方法
tmpList.remove(tmpList.size() - 1);
}
public int getValue(List<Integer> numList) {
int tmp = 1, sum = 0;
for (int i = numList.size() - 1; i >= 0; --i) {
sum += numList.get(i) * tmp;
tmp *= 10;
}
return sum;
}
public int sumNumbers(TreeNode root) {
List<List<Integer>> results = new ArrayList<>();
List<Integer> tmpList= new ArrayList<>();
dfs(root, tmpList, results);
int sum = 0;
for (int i = 0; i <= results.size() - 1; ++i) {
sum += getValue(results.get(i));
}
return sum;
}
}