๋ฌธ์
ํ์ด ๊ณผ์
๋ฃจํธ ๋
ธ๋๋ถํฐ ์์ํด์ ์ ๋
ธ๋๊น์ง์ ๊ฒฝ๋ก ์ค ํฉ์ด S
์ธ ๊ฒฝ์ฐ๊ฐ ์กด์ฌํ๋์ง ์ฐพ๋ ๋ฌธ์ ์
๋๋ค. DFS
๋ฅผ ํ์ฉํด์ ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ํ์ํ ์ ์์ผ๋ฉฐ ๋ฃจํธ ๋
ธ๋ ๋ฐฐ์ด์ด ๋น์ด์๋ ๊ฒฝ์ฐ์ ์ ์ํ๋ฉด ์ฝ๊ฒ ํด๊ฒฐํ ์ ์์ต๋๋ค.
์ฝ๋
/**
* 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) {
function isLeaf(root) {
return root.left === null && root.right === null;
}
function isNotEmpty(root) {
return root !== null;
}
function dfs(root, sum) {
if (isLeaf(root)) {
return sum + root.val === targetSum;
}
let isSatisfied = false;
if (root.left !== null) {
isSatisfied = dfs(root.left, sum + root.val);
}
if (root.right !== null) {
isSatisfied = isSatisfied || dfs(root.right, sum + root.val);
}
return isSatisfied;
}
const answer = isNotEmpty(root) && dfs(root, 0);
return answer;
};
๋ฐ์ํ
'๐ algorithm > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode 1578 - Minimum Deletion Cost to Avoid Repeating Letters (Medium) (0) | 2021.03.08 |
---|---|
LeetCode 904 - Fruit Into Baskets (Medium) (0) | 2021.03.08 |
LeetCode 63 - Unique Paths II (Medium) (0) | 2021.03.04 |
LeetCode 1011 - Capacity To Ship Packages Within D Days (Medium) (0) | 2021.03.04 |
LeetCode 881 - Boats to Save People (Medium) (0) | 2021.03.04 |
๐ฌ ๋๊ธ