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

LeetCode 101 - Symmetric Tree (Easy)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 101๋ฒˆ

ํ’€์ด ๊ณผ์ •

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

์ด๋ฅผ ์œ„ํ•ด์„œ ๋Œ€์นญ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ํŠธ๋ฆฌ๋ฅผ ํ•˜๋‚˜ ์˜ˆ์‹œ๋กœ ๊ทธ๋ ค์„œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์„ค๊ณ„ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

์œ„์™€ ๊ฐ™์ด ๋Œ€์นญ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ํŠธ๋ฆฌ๋ฅผ ์–ด๋–ค ๋ฐฉ๋ฒ•์œผ๋กœ ํŒ๋‹จํ•ด์ค„ ์ˆ˜ ์žˆ์„๊นŒ์š”?

์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ๊ฒ ์ง€๋งŒ ์ €๋Š” ํŠธ๋ฆฌ์˜ ์ˆœํšŒ๋ฅผ ์‘์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

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

๋งŒ์•ฝ ํ•ด๋‹น ํŠธ๋ฆฌ๊ฐ€ ๋Œ€์นญ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๋ฉด ๋‘ ์ˆœํšŒ ๊ฒฐ๊ณผ๊ฐ€ ๋™์ผํ•ด์•ผํ•˜๋ฏ€๋กœ ์ด๋ฅผ ํ™œ์šฉํ•ด ํŠธ๋ฆฌ์˜ ๋Œ€์นญ ์œ ๋ฌด๋ฅผ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

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

์ฝ”๋“œ

/**
 * 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)
 * }
 */

function traversal_with_mode(root, visit, mode) {
  if (root === null) {
    visit.push(null);
    return;
  }

  visit.push(root.val);
  if (mode === "left") {
    traversal_with_mode(root.left, visit, mode);
    traversal_with_mode(root.right, visit, mode);
  } else {
    traversal_with_mode(root.right, visit, mode);
    traversal_with_mode(root.left, visit, mode);
  }
}

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isSymmetric = function (root) {
  let left_trace = [];
  let right_trace = [];

  traversal_with_mode(root, left_trace, "left");
  traversal_with_mode(root, right_trace, "right");

  // ๋‘ ๋ฐฉ๋ฌธ ๊ฒฐ๊ณผ๋ฅผ ๋น„๊ตํ•œ๋‹ค.
  if (left_trace.length !== right_trace.length) {
    return false;
  } else {
    for (let i = 0; i < left_trace.length; i++) {
      if (left_trace[i] !== right_trace[i]) {
        return false;
      }
    }
  }

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

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

LeetCode 62 - Unique Paths (Medium)  (0) 2021.03.02
LeetCode 121 - Best Time to Buy and Sell Stock (Easy)  (0) 2021.03.02
LeetCode 876 - Middle of the Linked List (Easy)  (0) 2021.03.02
LeetCode 221 - Maximal Square (Medium)  (0) 2021.03.02
LeetCode 543 - Diameter of Binary Tree (Easy)  (1) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€