路径总和 (Path Sum)

 

思路:

// @Title: 路径总和 (Path Sum)
// @Author: qisiii
// @Date: 2024-09-15 17:29:16
// @Runtime: 0 ms
// @Memory: 42.1 MB
// @comment: 
// @flag: 
/**
 * 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){
            if(root.left==null&&root.right==null&&root.val==targetSum){
                return true;
            }
           return hasPathSum(root.left,targetSum-root.val)||hasPathSum(root.right,targetSum-root.val);
        }
        return false;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18