Skip to content

Commit e03925c

Browse files
committed
add: solve #226 Invert Binary Tree with ts
1 parent 88214b4 commit e03925c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* ์ด์ง„ ํŠธ๋ฆฌ๋ฅผ ๋ฐ˜์ „์‹œํ‚ค๋Š” ํ•จ์ˆ˜
3+
* @param {TreeNode | null} root - ๋ฐ˜์ „ํ•  ์ด์ง„ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ ๋…ธ๋“œ
4+
* @returns {TreeNode | null} - ๋ฐ˜์ „๋œ ์ด์ง„ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ ๋…ธ๋“œ
5+
*
6+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
7+
* - ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์„ ํ˜• ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง
8+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(h)
9+
* - ์žฌ๊ท€ ํ˜ธ์ถœ์— ์˜ํ•ด ์ตœ๋Œ€ ํŠธ๋ฆฌ์˜ ๋†’์ด(h)๋งŒํผ์˜ ํ˜ธ์ถœ ์Šคํƒ์ด ํ•„์š”
10+
*/
11+
function invertTree(root: TreeNode | null): TreeNode | null {
12+
// ๋ฃจํŠธ๊ฐ€ null์ด๋ฉด null ๋ฐ˜ํ™˜
13+
if (!root) return null;
14+
15+
// ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ๋ฐ˜์ „
16+
const left = invertTree(root.left);
17+
const right = invertTree(root.right);
18+
19+
// ํ˜„์žฌ ๋…ธ๋“œ์˜ ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ๊ตํ™˜
20+
root.left = right;
21+
root.right = left;
22+
23+
// ๋ฐ˜์ „๋œ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๋ฐ˜ํ™˜
24+
return root;
25+
}
26+

0 commit comments

Comments
ย (0)