Sum Root to Leaf Numbers
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;如果遇到空节点,则返回数值0。
2.代码
public class Solution {
public int sumNumbers(TreeNode root) {
return sum(root,0);
}
private int sum(TreeNode root, int cur){
if(root==null) return 0;
cur=10*cur+root.val;
if(root.left==null&&root.right==null)
return cur;
else
return sum(root.left,cur)+sum(root.right,cur);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。