Skip to content

Commit 247014d

Browse files
committed
add Invert Binary Tree solution
1 parent 11f3506 commit 247014d

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

invert-binary-tree/HoonDongKang.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* [Problem]: [226] Invert Binary Tree
3+
* (https://leetcode.com/problems/invert-binary-tree/)
4+
*/
5+
6+
class TreeNode {
7+
val: number;
8+
left: TreeNode | null;
9+
right: TreeNode | null;
10+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
11+
this.val = val === undefined ? 0 : val;
12+
this.left = left === undefined ? null : left;
13+
this.right = right === undefined ? null : right;
14+
}
15+
}
16+
17+
function invertTree(root: TreeNode | null): TreeNode | null {
18+
// 시간복잡도 O(n)
19+
// 공간복잡도 O(n)
20+
function recursiveFunc(root: TreeNode | null): TreeNode | null {
21+
if (root === null) {
22+
return null;
23+
}
24+
25+
const temp = root.left;
26+
root.left = invertTree(root.right);
27+
root.right = invertTree(temp);
28+
29+
return root;
30+
}
31+
// 시간복잡도 O(n)
32+
// 공간복잡도 O(n)
33+
function stackFunc(root: TreeNode | null): TreeNode | null {
34+
if (root === null) {
35+
return null;
36+
}
37+
38+
const stack: Array<TreeNode | null> = [root];
39+
40+
while (stack.length > 0) {
41+
const node = stack.pop()!;
42+
43+
if (node === null) {
44+
continue;
45+
}
46+
47+
[node.left, node.right] = [node.right, node.left];
48+
stack.push(node.left, node.right);
49+
}
50+
51+
return root;
52+
}
53+
}

0 commit comments

Comments
 (0)