forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHoonDongKang.ts
More file actions
53 lines (44 loc) · 1.34 KB
/
HoonDongKang.ts
File metadata and controls
53 lines (44 loc) · 1.34 KB
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
/**
* [Problem]: [226] Invert Binary Tree
* (https://leetcode.com/problems/invert-binary-tree/)
*/
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;
}
}
function invertTree(root: TreeNode | null): TreeNode | null {
// 시간복잡도 O(n)
// 공간복잡도 O(n)
function recursiveFunc(root: TreeNode | null): TreeNode | null {
if (root === null) {
return null;
}
const temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}
// 시간복잡도 O(n)
// 공간복잡도 O(n)
function stackFunc(root: TreeNode | null): TreeNode | null {
if (root === null) {
return null;
}
const stack: Array<TreeNode | null> = [root];
while (stack.length > 0) {
const node = stack.pop()!;
if (node === null) {
continue;
}
[node.left, node.right] = [node.right, node.left];
stack.push(node.left, node.right);
}
return root;
}
}