From b45652512b58a21a73a00fd8a15fca2d774e62b9 Mon Sep 17 00:00:00 2001 From: suhwan2004 Date: Mon, 30 Dec 2024 20:55:45 +0900 Subject: [PATCH] commit --- suhwan2004/Path Sum.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 suhwan2004/Path Sum.js diff --git a/suhwan2004/Path Sum.js b/suhwan2004/Path Sum.js new file mode 100644 index 0000000..50dfb7f --- /dev/null +++ b/suhwan2004/Path Sum.js @@ -0,0 +1,27 @@ +/* +18:30 ~ 18:49 +Time : O(N) +Space : O(N) +ALGO : dfs +DS : tree +Constraints : +- 트리 노드들의 갯수는 0개에서 5000개 사이 +- -1000 <= Node.val <= 1000 +- -1000 <= targetSum <= 1000 +Edge Case : root가 없을 시에 바로 false +*/ + +var hasPathSum = function(root, targetSum) { + if(!root) return false + return dfs(root, 0, targetSum) +}; + +const dfs = (node, sum, targetSum) => { + let curSum = sum + node.val + if(!node.left && !node.right) return targetSum === curSum + + const leftRes = node.left ? dfs(node.left, curSum, targetSum) : false + const rightRes = node.right ? dfs(node.right, curSum, targetSum) : false + + return leftRes || rightRes +} \ No newline at end of file