Skip to content

Commit 75e2583

Browse files
authored
Merge pull request #2276 from smosco/main
[smosco] WEEK 10 solutions
2 parents 621c6d8 + c626f53 commit 75e2583

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
10+
/**
11+
* ํ’€์ด 1: ์žฌ๊ท€ (Recursive)
12+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n) - ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ
13+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n) - ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ (์ตœ์•…์˜ ๊ฒฝ์šฐ ํŠธ๋ฆฌ ๋†’์ด๋งŒํผ)
14+
*
15+
* @param {TreeNode} root
16+
* @return {TreeNode}
17+
*/
18+
const invertTree = (root) => {
19+
if (!root) return null;
20+
21+
// ์ขŒ์šฐ ์ž์‹์„ ์žฌ๊ท€์ ์œผ๋กœ ๋ฐ˜์ „ํ•˜๋ฉด์„œ ๊ต์ฒด
22+
[root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
23+
24+
return root;
25+
};
26+
27+
/**
28+
* ํ’€์ด 2: ๋ฐ˜๋ณต (Iterative) - ์Šคํƒ ์‚ฌ์šฉ
29+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n) - ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ
30+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n) - ์Šคํƒ์— ๋…ธ๋“œ ์ €์žฅ
31+
*
32+
* @param {TreeNode} root
33+
* @return {TreeNode}
34+
*/
35+
const invertTreeIterative = (root) => {
36+
if (!root) return null;
37+
38+
const stack = [root];
39+
40+
while (stack.length > 0) {
41+
const node = stack.pop();
42+
43+
// ์ขŒ์šฐ ์ž์‹ ๊ต์ฒด
44+
[node.left, node.right] = [node.right, node.left];
45+
46+
// null์ด ์•„๋‹Œ ์ž์‹๋“ค์„ ์Šคํƒ์— ์ถ”๊ฐ€
47+
if (node.left) stack.push(node.left);
48+
if (node.right) stack.push(node.right);
49+
}
50+
51+
return root;
52+
};

0 commit comments

Comments
ย (0)