diff --git a/solutions/pathSum.test.ts b/solutions/pathSum.test.ts new file mode 100644 index 0000000..e871a5f --- /dev/null +++ b/solutions/pathSum.test.ts @@ -0,0 +1,16 @@ +import { createBinaryTreeNode } from "../utilities/TreeNode"; +import pathSum from "./pathSum"; + +describe("112. Path Sum", () => { + const TEST_CASES = new Map<[(number | null)[], number], boolean>([ + [[[5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], 22], true], + [[[5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], 20], false], + [[[], 0], false] + ]); + + for (const [[values, sum], expected] of TEST_CASES) { + it(`returns ${expected} when called with [${values}] and ${sum}`, () => { + expect(pathSum(createBinaryTreeNode(values), sum)).toBe(expected); + }); + } +}); diff --git a/solutions/pathSum.ts b/solutions/pathSum.ts new file mode 100644 index 0000000..caf48cc --- /dev/null +++ b/solutions/pathSum.ts @@ -0,0 +1,19 @@ +import { TreeNode } from "../utilities/TreeNode"; + +// 112. Path Sum +// https://leetcode.com/problems/path-sum/ +export default function hasPathSum( + root: TreeNode | null, + sum: number +): boolean { + // ⚠️ as following the test cases, we need to return false for hasPathSum(null, 0) + // so it cannot be just `if (root === null) return sum === 0` + if (root === null) return false; + if (root.left === null && root.right === null) return root.val === sum; + + // subtract self value and check the the leaf's value matches with sum + return ( + hasPathSum(root.left, sum - root.val) || + hasPathSum(root.right, sum - root.val) + ); +}