?
代码实现:
第一次写的错误代码:
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
targetSum = targetSum - root.val;
if (root.left == null && root.right == null){
if (targetSum == 0){
return true;
}
}
hasPathSum(root.left,targetSum);
hasPathSum(root.right,targetSum);
return false;
}
第二次改正后:
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
targetSum = targetSum - root.val;
if (root.left == null && root.right == null){
if (targetSum == 0){
return true;
}
}
return hasPathSum(root.left,targetSum) || hasPathSum(root.right,targetSum);
}
?对比这两次,希望对递归的理解更加深刻。
|