112. 路径总和


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


注意几点:
1,路径是从根节点到叶子节点
2,只要找到一条就行。



    public boolean hasPathSum(TreeNode root, int targetSum) {
        // root==null是由于节点只有一个孩子,执行到left,right,就会出现root==null
        // 因为不是叶子节点,所以这个条路径可以直接返回false.
        if(root == null) {
            return false;
        }

        if(root.left == null && root.right == null) {
            if(root.val == targetSum) {
                return true;
            } else {
                return false;
            }
        }
        return hasPathSum(root.left,targetSum-root.val) || hasPathSum(root.right, targetSum-root.val);

    }
posted @ 2022-02-23 21:16  一颗青菜  阅读(3)  评论(0)    收藏  举报