The path sum is judged whether there is to the leaf node and the sum is equal to a certain value

The path sum is judged whether there is to the leaf node and the sum is equal to a certain value

/**
 * 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;
        }
        return hasPathSumHelp(root, targetSum);
        
    }
    public boolean hasPathSumHelp(TreeNode root, int targetSum){
    
    
        if(root==null){
    
    
            return false;
        }
        if(root.left==null&&root.right==null&&root.val==targetSum){
    
    
            return true;
        }
        return hasPathSumHelp(root.left, targetSum-root.val)||hasPathSumHelp(root.right, targetSum-root.val);
    }
}

Guess you like

Origin blog.csdn.net/xiaomagezuishuai/article/details/114435613