112. 路径总和

题目:

思路:

【1】重点在于这句【叶子节点 是指没有子节点的节点】即 root.left == null && root.right == null

代码展示:

//时间0 ms 击败 100%
//内存42.3 MB 击败 35.11%
/**
 * 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.left == null && root.right == null) {
            return targetSum == root.val;
        }
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }
}

 

posted @ 2023-07-11 12:35  忧愁的chafry  阅读(5)  评论(0编辑  收藏  举报