forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYoungSeok-Choi.java
More file actions
71 lines (52 loc) · 1.5 KB
/
YoungSeok-Choi.java
File metadata and controls
71 lines (52 loc) · 1.5 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.HashMap;
import java.util.Map;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
// tc -> O(n)
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.right = left;
root.left = right;
return root;
}
}
// NOTE: deep copy 작업도 해볼 것
// 같은 val의 Node가 여러 개 들어오는 경우를 고려하지 못했음..
class WrongSolution {
public Map<Integer, TreeNode> tMap = new HashMap<>();
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
int rVal = root.val;
tMap.computeIfAbsent(rVal, k -> new TreeNode(k));
TreeNode cur = tMap.get(rVal);
if (root.left != null) {
tMap.computeIfAbsent(root.left.val, k -> new TreeNode(k));
cur.right = tMap.get(root.left.val);
invertTree(root.left);
}
if (root.right != null) {
tMap.computeIfAbsent(root.right.val, k -> new TreeNode(k));
cur.left = tMap.get(root.right.val);
invertTree(root.right);
}
return tMap.get(root.val);
}
}