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作为参数进行传递。遇到leaf的话就把sum*10+node.val返回。sum*10就是这题的要点了。
这里有一个比较详尽的想法。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
if(root == null)
return 0;
return sumNumbers(root, 0);
}
public int sumNumbers(TreeNode node, int sum){
if(node == null)
return 0;
if(node.left == null && node.right == null)
return sum * 10 + node.val;
return sumNumbers(node.left, sum * 10 + node.val) + sumNumbers(node.right, sum * 10 + node.val);
}
}