# Middle-题目46：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.

public class Solution {
private int currentTotal = 0;
public int sumNumbers(TreeNode root) {
dfs(root,0);
return currentTotal;
}
private void dfs(TreeNode node, int currentSum) {
if(node == null)
return;
else if(isLeaf(node)) {
currentSum+=node.val;
currentTotal+=currentSum;
}
else {
currentSum+=node.val;
dfs(node.left,currentSum*10);
dfs(node.right,currentSum*10);
}
}
private boolean isLeaf(TreeNode node) {
return node.left==null && node.right==null;
}
}

1ms,beats 28.93%,众数1ms,60.87%

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目46：129. Sum Root to Leaf Numbers 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)