输入: [1,2,3] 1 / 2 3 输出: 25 解释: 从根到叶子节点路径代表数字
. 从根到叶子节点路径
代表数字
. 因此,数字总和 = 12 + 13 = 25
class Solution {
public int sumNumbers(TreeNode root) {
return sum(root, 0);
}
private int sum(TreeNode n, int s) {
if (n == null)
return 0;
if (n.right == null && n.left == null)
return s * 10 + n.val;
return sum(n.left, s * 10 + n.val) + sum(n.right, s * 10 + n.val);
}
}
原文:https://www.cnblogs.com/MarkLeeBYR/p/10536139.html