leetcode112_路经总和

题目链接:
这是一道典型的,只需要对部分树进行搜索的题目,那么递归函数的返回值不能为void而为true。
还有一个技巧,为了处理方便不用进行求和,而是做减法即可。

递归1.0

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        return dfs(root, targetSum-root.val);
    }
    private boolean dfs(TreeNode root, int targetSum) {
        if(root.left == null && root.right == null) {
            if(targetSum == 0) return true;
        }
        if(root.left != null) {
            if(dfs(root.left, targetSum-root.left.val)) return true;
        }
        if(root.right != null) {
            if(dfs(root.right, targetSum-root.right.val)) return true;
        }
        return false;
    }
}

递归2.0

发现dfs函数和主函数签名一样,那么可以精简到一个函数:

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        targetSum -= root.val;
        if(root.left == null && root.right == null) {
            if(targetSum == 0) return true;
        }
        if(root.left != null) {
            if(hasPathSum(root.left, targetSum)) return true;
        }
        if(root.right != null) {
            if(hasPathSum(root.right, targetSum)) return true;
        }
        return false;
    }
}

递归3.0

发现在开头和单层逻辑体里都判断了null,可以精简

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        targetSum -= root.val;
        if(root.left == null && root.right == null) {
            if(targetSum == 0) return true;
        }
        if(hasPathSum(root.left, targetSum)) return true;
        if(hasPathSum(root.right, targetSum)) return true;
        return false;
    }
}

递归4.0

还可以发现最后三局还可以用短路运算逻辑符||进行精简:

posted @ 2022-03-06 13:15  明卿册  阅读(14)  评论(0编辑  收藏  举报