Skip to content

Commit c2acf66

Browse files
author
Kohei Asai
authored
112. Path Sum (#101)
1 parent 8387d20 commit c2acf66

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

solutions/pathSum.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { createBinaryTreeNode } from "../utilities/TreeNode";
2+
import pathSum from "./pathSum";
3+
4+
describe("112. Path Sum", () => {
5+
const TEST_CASES = new Map<[(number | null)[], number], boolean>([
6+
[[[5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], 22], true],
7+
[[[5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], 20], false],
8+
[[[], 0], false]
9+
]);
10+
11+
for (const [[values, sum], expected] of TEST_CASES) {
12+
it(`returns ${expected} when called with [${values}] and ${sum}`, () => {
13+
expect(pathSum(createBinaryTreeNode(values), sum)).toBe(expected);
14+
});
15+
}
16+
});

solutions/pathSum.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { TreeNode } from "../utilities/TreeNode";
2+
3+
// 112. Path Sum
4+
// https://leetcode.com/problems/path-sum/
5+
export default function hasPathSum(
6+
root: TreeNode<number> | null,
7+
sum: number
8+
): boolean {
9+
// ⚠️ as following the test cases, we need to return false for hasPathSum(null, 0)
10+
// so it cannot be just `if (root === null) return sum === 0`
11+
if (root === null) return false;
12+
if (root.left === null && root.right === null) return root.val === sum;
13+
14+
// subtract self value and check the the leaf's value matches with sum
15+
return (
16+
hasPathSum(root.left, sum - root.val) ||
17+
hasPathSum(root.right, sum - root.val)
18+
);
19+
}

0 commit comments

Comments
 (0)