Skip to content

Commit 05dfadb

Browse files
Merge pull request #111 from walkerrandolphsmith/feature/112-path-sum
solve problem
2 parents 7b89ce9 + 9b07de2 commit 05dfadb

2 files changed

Lines changed: 88 additions & 0 deletions

File tree

leet-code/112-path-sum/README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# 112-path-sum
2+
3+
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`.
4+
5+
A **leaf** is a node with no children.
6+
7+
---
8+
9+
### Example 1
10+
11+
**Input:**
12+
`root = [5,4,8,11,null,13,4,7,2,null,null,null,1]`
13+
`targetSum = 22`
14+
15+
**Output:**
16+
`true`
17+
18+
**Explanation:**
19+
The root-to-leaf path with the target sum is:
20+
5 → 4 → 11 → 2
21+
Sum = 22
22+
23+
### Example 2
24+
25+
**Input:**
26+
`root = [1,2,3]`
27+
`targetSum = 5`
28+
29+
**Output:**
30+
`false`
31+
32+
**Explanation:**
33+
There are two root-to-leaf paths in the tree:
34+
35+
1 → 2 : sum = 3
36+
1 → 3 : sum = 4
37+
There is no root-to-leaf path with sum = 5.
38+
39+
### Example 3
40+
41+
**Input:**
42+
`root = []`
43+
`targetSum = 0`
44+
45+
**Output:**
46+
`false`
47+
48+
**Explanation:**
49+
Since the tree is empty, there are no root-to-leaf paths.
50+
51+
---
52+
53+
### Constraints
54+
55+
- The number of nodes in the tree is in the range `[0, 5000]`.
56+
- `-1000 <= Node.val <= 1000`
57+
- `-1000 <= targetSum <= 1000`

leet-code/112-path-sum/index.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {number} targetSum
12+
* @return {boolean}
13+
*/
14+
var hasPathSum = function(root, targetSum) {
15+
// assume the target sum is not present in the tree
16+
// recrsively visit each node looking for a root-to-leaf sum that matches the target
17+
function visit(node, accumulation) {
18+
// defensive check to not process undefined or null nodes
19+
if (!node) return false;
20+
// sum the current node with the accumlated path value
21+
accumulation += node.val
22+
// determine if the node is a leaf node
23+
const isLeaf = !node.left && !node.right
24+
// mark the targetSum as found
25+
if (isLeaf && accumulation === targetSum) { return true }
26+
// visis the left and right subtree until the target is found or the paths have been exhausted
27+
return visit(node.left, accumulation) || visit(node.right, accumulation)
28+
}
29+
// begin the search at the root of the tree
30+
return visit(root, 0)
31+
};

0 commit comments

Comments
 (0)