LeetCode 129 Sum Root to Leaf Numbers
2014-08-13 09:26
441 查看
题目
Given a binary tree containing digits from
path could represent a number.
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
思路
1 看似很简单的题目,但是要把递归的逻辑弄清楚还是有点难度的。
2 一开始想过用广度遍历,每遍历一层,这层sum*10;可是发觉逻辑不对,并不是每一次数字都只用一次,也并不是每一层*10的次数都应该一样
3 后来想过前序遍历,可是在前序遍历中,碰到过的数字就会扔掉,没有办法保存路径,所以也不考虑了。
4 最后还是从计算本身来看,从一个节点出发,下降到左右节点,都是10*presum+val。如果这个节点是根节点,那么可以把前面那个数认为是个完整的数,加起来;如果本身是null,就什么都不做。
5 树的递归,并不是用几种方法硬去背诵的,而是要根据情况灵活应用。
代码
Given a binary tree containing digits from
0-9only, each root-to-leaf
path could represent a number.
An example is the root-to-leaf path
1->2->3which 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->2represents the number
12.
The root-to-leaf path
1->3represents 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_129_Sum Root to Leaf Numbers
- [LeetCode#129]Sum Root to Leaf Numbers
- LeetCode_129 Sum Root to Leaf Numbers
- [Leetcode 39] 129 Sum Root to Leaf Numbers
- leetcode_question_129 Sum Root to Leaf Numbers
- leetcode[129] Sum Root to Leaf Numbers
- leetcode || 129、Sum Root to Leaf Numbers
- leetcode 129 —— Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers - LeetCode 129
- [LeetCode]129 Sum Root to Leaf Numbers
- leetcode-129 Sum Root to Leaf Numbers
- [LeetCode 129] Sum Root to Leaf Numbers
- LeetCode(129) Sum Root to Leaf Numbers
- LeetCode 129 Sum Root to Leaf Numbers
- leetcode[129]Sum Root to Leaf Numbers
- LeetCode 129: Sum Root to Leaf Numbers
- Java for LeetCode 129 Sum Root to Leaf Numbers
- [leetcode 129] Sum Root to Leaf Numbers
- LeetCode 129 Sum Root to Leaf Numbers
- [leetcode-129]Sum Root to Leaf Numbers(c++)