Skip to content

Commit e940453

Browse files
committed
add solution : 226. Invert Binary Tree
1 parent 356e622 commit e940453

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

โ€Žinvert-binary-tree/mmyeon.ts

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

Comments
ย (0)