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

LeetCode 236 - Lowest Common Ancestor of a Binary Tree (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 236๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ด์ง„ ํŠธ๋ฆฌ๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๊ณตํ†ต ์กฐ์ƒ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
์—ฌ๊ธฐ์„œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์กฐ์ƒ ๋…ธ๋“œ๊ฐ€ ๋˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ์˜ ํ˜•ํƒœ๋ฅผ ๊ฐ€์ง‘๋‹ˆ๋‹ค.

    q (A)    a (A)
   /        / \
  b        b   q
 /        /
p        p

์œ„ ๊ทธ๋ฆผ์—์„œ p & q ์˜ ๊ณตํ†ต ์กฐ์ƒ ์ค‘ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋…ธ๋“œ๋Š” ์ „์ž์˜ ๊ฒฝ์šฐ q ์ด๊ณ  ํ›„์ž์˜ ๊ฒฝ์šฐ a ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

์ด๋ฅผ ํ†ตํ•ด ์šฐ๋ฆฌ๊ฐ€ ์ฐพ๋Š” ์กฐ์ƒ ๋…ธ๋“œ A ๋Š” ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์— ๊ฐ๊ฐ p ํ˜น์€ q ๊ฐ€ ์กด์žฌํ•˜๊ฑฐ๋‚˜
์กฐ์ƒ ๋…ธ๋“œ A ๋ฅผ ํฌํ•จํ•˜๊ณ  ๋‚˜๋จธ์ง€ ํ•œ ๋…ธ๋“œ๊ฐ€ ์™ผ์ชฝ ํ˜น์€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์— ์กด์žฌํ•˜๋Š” ํ˜•ํƒœ๋ฅผ ๊ฐ€์ง‘๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ DFS ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉฐ ์šฐ๋ฆฌ๊ฐ€ ์ฐพ๋Š” ํƒ€์ผ“ ๋…ธ๋“œ p, q ์˜ ์กด์žฌ ์œ ๋ฌด๋ฅผ ํŒ๋‹จํ•˜๊ณ 
ํ˜„์žฌ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ํฌํ•จํ•ด์„œ ์ž์‹๋“ค ์ค‘ p ํ˜น์€ q ๊ฐ€ ๋ชจ๋‘ ๋ฐœ๊ฒฌ๋˜๋Š” ์ฒซ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ์ฐพ์œผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
  let ancestor = null;

  function dfs(root, depth) {
    if (!root) return false;

    const here = root === p || root === q;
    const left = dfs(root.left, depth + 1);
    const right = dfs(root.right, depth + 1);

    if ([here, left, right].filter((x) => x).length === 2) {
      ancestor = root;
    }

    return here || left || right;
  }

  dfs(root, 0);

  return ancestor;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 763 - Partition Labels (Medium)  (0) 2021.03.04
LeetCode 48 - Rotate Image (Medium)  (0) 2021.03.04
LeetCode 494 - Target Sum (Medium)  (0) 2021.03.04
LeetCode 187 - Repeated DNA Sequences (Medium)  (0) 2021.03.03
LeetCode 3 - Longest Substring Without Repeating Characters (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€