forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYjason-K.ts
More file actions
26 lines (22 loc) ยท 883 Bytes
/
Yjason-K.ts
File metadata and controls
26 lines (22 loc) ยท 883 Bytes
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
/**
* ์ด์ง ํธ๋ฆฌ๋ฅผ ๋ฐ์ ์ํค๋ ํจ์
* @param {TreeNode | null} root - ๋ฐ์ ํ ์ด์ง ํธ๋ฆฌ์ ๋ฃจํธ ๋
ธ๋
* @returns {TreeNode | null} - ๋ฐ์ ๋ ์ด์ง ํธ๋ฆฌ์ ๋ฃจํธ ๋
ธ๋
*
* ์๊ฐ ๋ณต์ก๋: O(n)
* - ํธ๋ฆฌ์ ๋ชจ๋ ๋
ธ๋๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธํด์ผ ํ๋ฏ๋ก ์ ํ ์๊ฐ ๋ณต์ก๋๋ฅผ ๊ฐ์ง
* ๊ณต๊ฐ ๋ณต์ก๋: O(h)
* - ์ฌ๊ท ํธ์ถ์ ์ํด ์ต๋ ํธ๋ฆฌ์ ๋์ด(h)๋งํผ์ ํธ์ถ ์คํ์ด ํ์
*/
function invertTree(root: TreeNode | null): TreeNode | null {
// ๋ฃจํธ๊ฐ null์ด๋ฉด null ๋ฐํ
if (!root) return null;
// ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ์ฌ๊ท์ ์ผ๋ก ๋ฐ์
const left = invertTree(root.left);
const right = invertTree(root.right);
// ํ์ฌ ๋
ธ๋์ ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ๊ตํ
root.left = right;
root.right = left;
// ๋ฐ์ ๋ ๋ฃจํธ ๋
ธ๋๋ฅผ ๋ฐํ
return root;
}