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

LeetCode 226 - Invert Binary Tree (Easy)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 226๋ฒˆ

ํ’€์ด ๊ณผ์ •

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

๋‹ค๋ฅธ๋ถ„๋“ค์˜ ํ’€์ด๋ฒ•์„ ๋ณด๋‹ˆ level order traversal ์„ ์‚ฌ์šฉํ•˜์‹  ๋ถ„๋“ค๋„ ์žˆ์—ˆ์ง€๋งŒ ์ €๋Š” dfs ๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

๊ฐ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์™€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ invert ํ•ด์ค€ ๋‹ค์Œ
ํ•ด๋‹น ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ฃจํŠธ๋…ธ๋“œ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ค๋‹ˆ๋‹ค.

์ด๋Ÿฌํ•œ ์žฌ๊ท€ ํ˜ธ์ถœ์„ ๋ฐ˜๋ณตํ•˜๋ฉด ์ตœ์ข…์ ์œผ๋กœ ๊ธฐ์กด์˜ root ๋Š” invert ๋œ ํŠธ๋ฆฌ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * 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
 * @return {TreeNode}
 */
var invertTree = function (root) {
  function invert(root) {
    if (!root) return null;

    const left = invert(root.left);
    const right = invert(root.right);

    [root.left, root.right] = [right, left];

    return root;
  }

  invert(root);

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

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

LeetCode 98 - Validate Binary Search Tree (Medium)  (0) 2021.03.03
LeetCode 130 - Surrounded Regions (Medium)  (0) 2021.03.03
LeetCode 406 - Queue Reconstruction by Height (Medium)  (0) 2021.03.03
LeetCode 54 - Spiral Matrix (Medium)  (0) 2021.03.03
LeetCode 279 - Perfect Squares (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€