import java.util.*;
public class Solution {
public int sumNumbers (TreeNode root) {
// 预处理
if (root == null) return 0;
if (isLeaf(root)) return root.val;
// 返回所有路径的和
return getAllPathSum(root.left,root.val) + getAllPathSum(root.right,root.val);
}
// 深度优先搜索
public int getAllPathSum(TreeNode root, int fatherVal) {
// 预处理
if (root == null) return 0;
if (isLeaf(root)) return 10 * fatherVal + root.val;
// 更新路径在当前结点时的值
int curVal = fatherVal * 10 + root.val;
// 递归求左右子树的路径和
return getAllPathSum(root.left,curVal) + getAllPathSum(root.right,curVal);
}
// 判断当前结点是否为叶子结点
public static boolean isLeaf(TreeNode node) {
// 预处理
if (node == null) return false;
// 若当前结点没有子结点,则其为叶子结点
return node.left == null && node.right == null;
}
}