|
| 1 | +class TreeNode { |
| 2 | + val: number; |
| 3 | + left: TreeNode | null; |
| 4 | + right: TreeNode | null; |
| 5 | + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 6 | + this.val = val === undefined ? 0 : val; |
| 7 | + this.left = left === undefined ? null : left; |
| 8 | + this.right = right === undefined ? null : right; |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +/** |
| 13 | + * @link https://leetcode.com/problems/invert-binary-tree/description/ |
| 14 | + * |
| 15 | + * ์ ๊ทผ ๋ฐฉ๋ฒ : ๊น์ด ์ฐ์ ํ์(DFS) ์ฌ์ฉ |
| 16 | + * - ๊ฐ ๋
ธ๋์ ์ข์ฐ ์์ ๋
ธ๋ swap ์งํ |
| 17 | + * - ์ผ์ชฝ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์ ๋ํด ์ฌ๊ท์ ์ผ๋ก ํธ์ถ |
| 18 | + * |
| 19 | + * ์๊ฐ๋ณต์ก๋ : O(n) |
| 20 | + * - n์ ๋
ธ๋์ ๊ฐ์, ์ฃผ์ด์ง ๋
ธ๋ ๋งํผ ์ํ |
| 21 | + * |
| 22 | + * ๊ณต๊ฐ๋ณต์ก๋ : O(h) |
| 23 | + * - h : ํธ๋ฆฌ์ ๋์ด |
| 24 | + * - ํธ์ถ ์คํ ์ต๋ ํธ๋ฆฌ ๋์ด๋งํผ ์์ |
| 25 | + */ |
| 26 | +function invertTree(root: TreeNode | null): TreeNode | null { |
| 27 | + if (!root) return root; |
| 28 | + |
| 29 | + [root.left, root.right] = [root.right, root.left]; |
| 30 | + invertTree(root.left); |
| 31 | + invertTree(root.right); |
| 32 | + |
| 33 | + return root; |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * |
| 38 | + * ์ ๊ทผ ๋ฐฉ๋ฒ : ๋๋น ์ฐ์ ํ์(BFS) ์ฌ์ฉ |
| 39 | + * - root ๋
ธ๋๋ฅผ ํ์ ๋ด๊ณ , ํ๊ฐ ๋น ๋๊น์ง ์ข์ฐ ์์ ๋
ธ๋ swap๊ณผ ํ์ ์ถ๊ฐ ํ๋ ๋ก์ง ๋ฐ๋ณตํ๊ธฐ |
| 40 | + * |
| 41 | + * ์๊ฐ๋ณต์ก๋ : O(n) |
| 42 | + * - n: ํธ๋ฆฌ ๋
ธ๋์ ๊ฐ์ |
| 43 | + * - ๋ชจ๋ ๋
ธ๋๋ฅผ ํ ๋ฒ ์ฉ ๋ฐฉ๋ฌธํ๊ณ swap ์์
์งํ |
| 44 | + * |
| 45 | + * ๊ณต๊ฐ๋ณต์ก๋ : O(n) |
| 46 | + * - ์ต์
์ ๊ฒฝ์ฐ ์น์ฐ์น ํธ๋ฆฌ์ธ ๊ฒฝ์ฐ ๋ชจ๋ ๋
ธ๋ ์์ฐจ์ ์ผ๋ก ํ์ ์ ์ฅ |
| 47 | + */ |
| 48 | +function invertTree(root: TreeNode | null): TreeNode | null { |
| 49 | + if (!root) return root; |
| 50 | + |
| 51 | + const queue = [root]; |
| 52 | + |
| 53 | + while (queue.length) { |
| 54 | + const node = queue.shift()!; |
| 55 | + |
| 56 | + [node.left, node.right] = [node.right, node.left]; |
| 57 | + |
| 58 | + if (node.left) queue.push(node.left); |
| 59 | + if (node.right) queue.push(node.right); |
| 60 | + } |
| 61 | + |
| 62 | + return root; |
| 63 | +} |
0 commit comments