๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 112 - Path Sum (Easy)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 112๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋ฃจํŠธ ๋…ธ๋“œ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ์žŽ ๋…ธ๋“œ๊นŒ์ง€์˜ ๊ฒฝ๋กœ ์ค‘ ํ•ฉ์ด 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;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€