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

LeetCode 617 - Merge Two Binary Trees (Easy)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 617๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋‘ ๊ฐœ์˜ ์ด์ง„ ํŠธ๋ฆฌ๋ฅผ ํ•ฉ์น˜๋Š” ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ง๊ด€์ ์œผ๋กœ ์ƒ๊ฐํ–ˆ์„๋•Œ๋Š” ์‰ฌ์šด๊ฑฐ ๊ฐ™์•˜๋Š”๋ฐ ์ƒ๊ฐ๋ณด๋‹ค ์–ด๋–ค ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•ด์•ผ ๋ช…ํ™•ํ• ์ง€ ๋งŽ์€ ๊ณ ๋ฏผ์„ ํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์ €๋Š” merge ๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ํ˜ธ์ถœํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ณ ์ž ํ–ˆ์Šต๋‹ˆ๋‹ค.
์šฐ์„  merge ์˜ ๊ธฐ์ค€์ด ๋˜๋Š” ํŠธ๋ฆฌ๋ฅผ main, ๋‚˜๋จธ์ง€๋ฅผ sub ๋กœ ๋‚˜๋ˆˆ
๋‹ค์Œ ๋‘ ํŠธ๋ฆฌ ๋ชจ๋‘ ํ˜„์žฌ ๋ฃจํŠธ ๋…ธ๋“œ๊ฐ€ ์กด์žฌํ•  ๊ฒฝ์šฐ main ์— ๊ฐ’์„ ๋”ํ–ˆ์Šต๋‹ˆ๋‹ค.

๋‹ค์Œ ์žฌ๊ท€ํ˜ธ์ถœ ์ „์— ๋จผ์ € ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•˜์˜€๊ณ 
๋‘ ํŠธ๋ฆฌ ๋ชจ๋‘ ๊ฐ๊ฐ ์™ผ์ชฝ ํ˜น์€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ์กด์žฌํ• ๋•Œ๋งŒ DFS ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ 
๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ์—๋Š” ๋ณ„๋„์˜ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์คฌ์Šต๋‹ˆ๋‹ค.

์—ฌ๊ธฐ์„œ ๋ณ„๋„์˜ ์ฒ˜๋ฆฌ๋ž€ main ์˜ ์™ผ์ชฝ(์˜ค๋ฅธ์ชฝ) ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋ฐ sub ์— ์กด์žฌํ•  ๊ฒฝ์šฐ๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

๋งˆ์ง€๋ง‰์œผ๋กœ merge ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์ฒซ ์‹œ์ ์—์„œ๋„ t1 ๊ณผ t2 ์ค‘์—์„œ
null ์ด ์•„๋‹Œ ํŠธ๋ฆฌ๋ฅผ main ์œผ๋กœ ์„ค์ •ํ•ด์„œ ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•˜๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * 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} t1
 * @param {TreeNode} t2
 * @return {TreeNode}
 */
var mergeTrees = function (t1, t2) {
  function merge(main, sub) {
    if (main && sub) main.val += sub.val;

    if (main && main.left && sub && sub.left) {
      merge(main.left, sub.left);
    } else if (sub && sub.left) {
      main.left = sub.left;
    }

    if (main && main.right && sub && sub.right) {
      merge(main.right, sub.right);
    } else if (sub && sub.right) {
      main.right = sub.right;
    }
  }

  if (t1) merge(t1, t2);
  else merge(t2, t1);

  const ans = t1 ? t1 : t2;

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

๐Ÿ’ฌ ๋Œ“๊ธ€