[Leetcode-Tree] Sum Root to Leaf Numbers
文章目录
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);
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论