129. Sum Root to Leaf Numbers
2016-10-07 23:05
246 查看
Given a binary tree containing digits from
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 =
关键点:数值都在0-9之间,
左边的和+右边的和 不用考虑复杂
直接左右同时递归求和
public class Solution {
public int sumNumbers(TreeNode root) {
return preorder(root,0);
}
public int preorder(TreeNode root,int s){
if(root==null) return 0;
if(root.left==null && root.right==null) return s*10+root.val;
return preorder(root.left,s*10+root.val)+preorder(root.right,s*10+root.val);
}
}
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.
关键点:数值都在0-9之间,
左边的和+右边的和 不用考虑复杂
直接左右同时递归求和
public class Solution {
public int sumNumbers(TreeNode root) {
return preorder(root,0);
}
public int preorder(TreeNode root,int s){
if(root==null) return 0;
if(root.left==null && root.right==null) return s*10+root.val;
return preorder(root.left,s*10+root.val)+preorder(root.right,s*10+root.val);
}
}
相关文章推荐
- [LeetCode129]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)SumRoottoLeafNumbers
- 129. Sum Root to Leaf Numbers
- LeetCode - 129 - Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- leetcode129---Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers LeetCode
- 129.leetcode Sum Root to Leaf Numbers(medium)[深度遍历DFS]
- LeetCode: Sum Root to Leaf Numbers [129]
- LeetCode(129) Sum Root to Leaf Numbers
- LeetCode 129:Sum Root to Leaf Numbers
- Leetcode OJ 129 Sum Root to Leaf Numbers [Medium]
- [LeetCode#129]Sum Root to Leaf Numbers
- 【LEETCODE】129-Sum Root to Leaf Numbers [Python]
- 129. Sum Root to Leaf Numbers**
- FTPrep, 129 Sum Root to Leaf Numbers
- leetcode 129 Sum Root to Leaf Numbers