From 8eab314c0ad821958dda4827abd84182cfe326f8 Mon Sep 17 00:00:00 2001 From: BangDori Date: Fri, 27 Dec 2024 21:42:06 +0900 Subject: [PATCH] [Leetcode - Easy] Path sum --- bangdori/Path Sum.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 bangdori/Path Sum.js diff --git a/bangdori/Path Sum.js b/bangdori/Path Sum.js new file mode 100644 index 0000000..6ac0e86 --- /dev/null +++ b/bangdori/Path Sum.js @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} targetSum + * @return {boolean} + */ +var hasPathSum = function (root, targetSum) { + let answer = false; + + const dfs = (tree, curr) => { + if (tree.left) dfs(tree.left, curr + tree.left.val); + if (tree.right) dfs(tree.right, curr + tree.right.val); + if (!tree.left && !tree.right && curr === targetSum) { + answer = true; + return; + } + }; + + if (root) dfs(root, root.val); + return answer; +};