129. Sum Root to Leaf Numbers
其实就是求路径的变形。首先确定递归的函数dfs,返回值为int。然后分情况讨论,节点为空返回0,最后一个节点返回res * 10 + root.val
,中间节点计算res * 10 + root.val
且继续调用dfs函数
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int res) {
if (root == null) return 0;
if (root.left == null && root.right == null) return 10 * res + root.val;
res = 10 * res + root.val;
return dfs(root.left, res) + dfs(root.right, res);
}