File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .HashMap ;
2+ import java .util .Map ;
3+
4+ class TreeNode {
5+ int val ;
6+ TreeNode left ;
7+ TreeNode right ;
8+
9+ TreeNode () {
10+ }
11+
12+ TreeNode (int val ) {
13+ this .val = val ;
14+ }
15+
16+ TreeNode (int val , TreeNode left , TreeNode right ) {
17+ this .val = val ;
18+ this .left = left ;
19+ this .right = right ;
20+ }
21+ }
22+
23+ // tc -> O(n)
24+ class Solution {
25+
26+ public TreeNode invertTree (TreeNode root ) {
27+ if (root == null )
28+ return null ;
29+
30+ TreeNode left = invertTree (root .left );
31+ TreeNode right = invertTree (root .right );
32+
33+ root .right = left ;
34+ root .left = right ;
35+
36+ return root ;
37+ }
38+
39+ }
40+
41+ // NOTE: deep copy 작업도 해볼 것
42+ // 같은 val의 Node가 여러 개 들어오는 경우를 고려하지 못했음..
43+ class WrongSolution {
44+
45+ public Map <Integer , TreeNode > tMap = new HashMap <>();
46+
47+ public TreeNode invertTree (TreeNode root ) {
48+ if (root == null )
49+ return null ;
50+
51+ int rVal = root .val ;
52+
53+ tMap .computeIfAbsent (rVal , k -> new TreeNode (k ));
54+
55+ TreeNode cur = tMap .get (rVal );
56+
57+ if (root .left != null ) {
58+ tMap .computeIfAbsent (root .left .val , k -> new TreeNode (k ));
59+ cur .right = tMap .get (root .left .val );
60+ invertTree (root .left );
61+ }
62+
63+ if (root .right != null ) {
64+ tMap .computeIfAbsent (root .right .val , k -> new TreeNode (k ));
65+ cur .left = tMap .get (root .right .val );
66+ invertTree (root .right );
67+ }
68+
69+ return tMap .get (root .val );
70+ }
71+ }
You can’t perform that action at this time.
0 commit comments