|
| 1 | +// Source : https://leetcode.com/problems/path-sum |
| 2 | +// Author : Dean Shi |
| 3 | +// Date : 2021-12-14 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * Given the root of a binary tree and an integer targetSum, return true if the tree |
| 7 | + * has a root-to-leaf path such that adding up all the values along the path equals |
| 8 | + * targetSum. |
| 9 | + * |
| 10 | + * A leaf is a node with no children. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * |
| 14 | + * Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 |
| 15 | + * Output: true |
| 16 | + * Explanation: The root-to-leaf path with the target sum is shown. |
| 17 | + * |
| 18 | + * Example 2: |
| 19 | + * |
| 20 | + * Input: root = [1,2,3], targetSum = 5 |
| 21 | + * Output: false |
| 22 | + * Explanation: There two root-to-leaf paths in the tree: |
| 23 | + * (1 --> 2): The sum is 3. |
| 24 | + * (1 --> 3): The sum is 4. |
| 25 | + * There is no root-to-leaf path with sum = 5. |
| 26 | + * |
| 27 | + * Example 3: |
| 28 | + * |
| 29 | + * Input: root = [], targetSum = 0 |
| 30 | + * Output: false |
| 31 | + * Explanation: Since the tree is empty, there are no root-to-leaf paths. |
| 32 | + * |
| 33 | + * Constraints: |
| 34 | + * |
| 35 | + * The number of nodes in the tree is in the range [0, 5000]. |
| 36 | + * -1000 <= Node.val <= 1000 |
| 37 | + * -1000 <= targetSum <= 1000 |
| 38 | + * |
| 39 | + * |
| 40 | + ***************************************************************************************/ |
| 41 | + |
| 42 | +/** |
| 43 | + * Definition for a binary tree node. |
| 44 | + * function TreeNode(val) { |
| 45 | + * this.val = val; |
| 46 | + * this.left = this.right = null; |
| 47 | + * } |
| 48 | + */ |
| 49 | +/** |
| 50 | + * @param {TreeNode} root |
| 51 | + * @param {number} sum |
| 52 | + * @return {boolean} |
| 53 | + */ |
| 54 | +var hasPathSum = function(root, sum) { |
| 55 | + if (!root) { |
| 56 | + return false; |
| 57 | + } |
| 58 | + const targetSum = sum - root.val |
| 59 | + if (targetSum === 0 && !root.left && !root.right) { |
| 60 | + return true |
| 61 | + } |
| 62 | + return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum) |
| 63 | +}; |
0 commit comments