Skip to content

112. Path Sum #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions solutions/pathSum.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
}
});
19 changes: 19 additions & 0 deletions solutions/pathSum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { TreeNode } from "../utilities/TreeNode";

// 112. Path Sum
// https://leetcode.com/problems/path-sum/
export default function hasPathSum(
root: TreeNode<number> | 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)
);
}