您的位置:首页 > 职场人生

LeetCode 129 Sum Root to Leaf Numbers

2014-08-13 09:26 441 查看
题目

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
.

思路

1 看似很简单的题目,但是要把递归的逻辑弄清楚还是有点难度的。

2 一开始想过用广度遍历,每遍历一层,这层sum*10;可是发觉逻辑不对,并不是每一次数字都只用一次,也并不是每一层*10的次数都应该一样

3 后来想过前序遍历,可是在前序遍历中,碰到过的数字就会扔掉,没有办法保存路径,所以也不考虑了。

4 最后还是从计算本身来看,从一个节点出发,下降到左右节点,都是10*presum+val。如果这个节点是根节点,那么可以把前面那个数认为是个完整的数,加起来;如果本身是null,就什么都不做。

5 树的递归,并不是用几种方法硬去背诵的,而是要根据情况灵活应用。

代码

public class Solution {
public int sumNumbers(TreeNode root) {
if(root == null){
return 0;
}
int[] ans = new int[1];
useme(root,ans,0);
return ans[0];
}

public void useme(TreeNode root , int[] ans,int presum){
if(root== null){
return ;
}
if(root.left ==null && root.right == null){
ans[0]+=presum*10+root.val;
}
useme(root.left,ans,presum*10+root.val);
useme(root.right,ans,presum*10+root.val);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 面试笔试