|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * function TreeNode(val, left, right) { |
| 4 | + * this.val = (val===undefined ? 0 : val) |
| 5 | + * this.left = (left===undefined ? null : left) |
| 6 | + * this.right = (right===undefined ? null : right) |
| 7 | + * } |
| 8 | + */ |
| 9 | + |
| 10 | +/** |
| 11 | + * ํ์ด 1: ์ฌ๊ท (Recursive) |
| 12 | + * ์๊ฐ ๋ณต์ก๋: O(n) - ๋ชจ๋ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธ |
| 13 | + * ๊ณต๊ฐ ๋ณต์ก๋: O(n) - ์ฌ๊ท ํธ์ถ ์คํ (์ต์
์ ๊ฒฝ์ฐ ํธ๋ฆฌ ๋์ด๋งํผ) |
| 14 | + * |
| 15 | + * @param {TreeNode} root |
| 16 | + * @return {TreeNode} |
| 17 | + */ |
| 18 | +const invertTree = (root) => { |
| 19 | + if (!root) return null; |
| 20 | + |
| 21 | + // ์ข์ฐ ์์์ ์ฌ๊ท์ ์ผ๋ก ๋ฐ์ ํ๋ฉด์ ๊ต์ฒด |
| 22 | + [root.left, root.right] = [invertTree(root.right), invertTree(root.left)]; |
| 23 | + |
| 24 | + return root; |
| 25 | +}; |
| 26 | + |
| 27 | +/** |
| 28 | + * ํ์ด 2: ๋ฐ๋ณต (Iterative) - ์คํ ์ฌ์ฉ |
| 29 | + * ์๊ฐ ๋ณต์ก๋: O(n) - ๋ชจ๋ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธ |
| 30 | + * ๊ณต๊ฐ ๋ณต์ก๋: O(n) - ์คํ์ ๋
ธ๋ ์ ์ฅ |
| 31 | + * |
| 32 | + * @param {TreeNode} root |
| 33 | + * @return {TreeNode} |
| 34 | + */ |
| 35 | +const invertTreeIterative = (root) => { |
| 36 | + if (!root) return null; |
| 37 | + |
| 38 | + const stack = [root]; |
| 39 | + |
| 40 | + while (stack.length > 0) { |
| 41 | + const node = stack.pop(); |
| 42 | + |
| 43 | + // ์ข์ฐ ์์ ๊ต์ฒด |
| 44 | + [node.left, node.right] = [node.right, node.left]; |
| 45 | + |
| 46 | + // null์ด ์๋ ์์๋ค์ ์คํ์ ์ถ๊ฐ |
| 47 | + if (node.left) stack.push(node.left); |
| 48 | + if (node.right) stack.push(node.right); |
| 49 | + } |
| 50 | + |
| 51 | + return root; |
| 52 | +}; |
0 commit comments