Skip to content

Latest commit

 

History

History
94 lines (85 loc) · 2.59 KB

112PathSum.org

File metadata and controls

94 lines (85 loc) · 2.59 KB

题目

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

imgs/pathsum1.jpg

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true

Example 2:

imgs/pathsum2.jpg

Input: root = [1,2,3], targetSum = 5
Output: false

Example 3:

Input: root = [1,2], targetSum = 0
Output: false

CPP

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (root == NULL) return false;

        // 题目要求的是叶子节点
        if (root->left == NULL && root->right == NULL) {
            return root->val == sum;
        }

        if (hasPathSum(root->left, sum - root->val)) {
            return true;
        }

        if (hasPathSum(root->right, sum - root->val)) {
            return true;
        }

        return false;
    }
};

Java

/**
 * 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 sum) {
        if (root == null) return false;
     
        if (root.left == null && root.right == null) {
            return root.val == sum;
        }
     
        if (hasPathSum(root.left, sum - root.val)) {
            return true;
        }
     
        if (hasPathSum(root.right, sum - root.val)) {
            return true;
        }
     
        return false;
    }
}