# Middle-题目46：129. Sum Root to Leaf Numbers

56人阅读 评论(0)

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%

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56163次
• 积分：3202
• 等级：
• 排名：第10668名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论