112. 路径总和

题目

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null)
        return false;
        if(root.right==null&&root.right==null&&root.val==targetSum)
        return true;   
        if(root.left==null)
        return hasPathSum(root.right,targetSum-root.val);
        if(root.right==null)
        return hasPathSum(root.left,targetSum-root.val);
        return hasPathSum(root.right,targetSum-root.val)||hasPathSum(root.left,targetSum-root.val);
        }
        
        
    }

反思

提交会发现出错了,因为由于判断左右子树是否为空的存在,导致截去了一部分结果。因此不应该对左、右子树是否为空做判断。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null)
        return false;
        if(root.right==null&&root.left==null&&root.val==targetSum)
        return true;   
        return hasPathSum(root.right,targetSum-root.val)||hasPathSum(root.left,targetSum-root.val);
        }
        
        
    }

上一篇:112. 路径总和


下一篇:力扣112. 路径总和