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