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
.
如果你对递归很熟悉的话,那么就会知道这个题可以用树的后序遍历。
一开始我想要不要递归成子问题,后来发现不太可行,比如2+3=5, 那么返回到根10*2+5=25,这样的话你得知道对于这个根节点有多少个子节点,每个节点的深度又不知道。。放弃
后来考虑到用后序遍历:每次递归到叶子(leaf),它的状态是,没有左和右节点。 那么我们记录一个subValue作为参数,告诉我们从上面传下来多少值。
比如说例子的左子树,1->2 那我从上面给的值是1,1*10+2 就可以,再往下走,没了,就返回一个12. 那么再把右子树的值加上,返回,就结束了。
当然,题里给我们一个函数subNumber(TreeNode root) ,是不足以完成递归的,因为我们不知道对于每个递归,上面给的值是多少,我们无法回去。
所以写一个新函数 int subSum(TreeNode cur, int subValue) 用来记录累加到多少了,再用subValue*10+cur.value 就得到了现在的值。如果是叶子了,那就返回,不是再继续往下走。注意我们还得加个判断,如果cur是null,我们要返回0,因为这种情况不是叶子节点,我们要让递归中止。
public class Solution {
public int sumNumbers(TreeNode root) {
if(root==null) return 0;
return subSum(root, 0);
}
public int subSum(TreeNode cur,int subValue){
if(cur==null) return 0;
if(cur.left==null && cur.right==null){
return subValue*10+cur.val;
}
int base=10;
return subSum(cur.left, subValue*base+cur.val)+
subSum(cur.right, subValue*base+cur.val);
}
}