题目描述
题解
递归:
终止条件:
- 当遇到叶子节点的时候,返回当前路径组合的值
- 当遇到空节点的时候,返回0( 一定要返回0)
处理逻辑: - 用target记录从根节点到当前节点的值,并作为参数传入下一个递归函数
- 如果不为空的话,target = target * 10 + root.val
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int target){
if (root == null) return 0;
target = target * 10 + root.val;
if (root.left == null && root.right == null){
return target;
}
return dfs(root.left, target) + dfs(root.right, target);
}
}