File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed
Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ ํ์ด 1
3+ - ํจ์์ ์ฌ๊ทํธ์ถ์ ์ด์ฉํด์ ํ์ดํ ์ ์์ต๋๋ค
4+
5+ Big O
6+ - N: ๋
ธ๋์ ๊ฐ์
7+ - H: ํธ๋ฆฌ์ ๋์ด
8+ - Time complexity: O(N)
9+ - Space complexity: O(H) (logN <= H <= N)
10+ - ์ฌ๊ท ํธ์ถ ์คํ์ ์ต๋ ๊น์ด๋ ํธ๋ฆฌ์ ๋์ด์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค
11+ */
12+
13+ /**
14+ * Definition for a binary tree node.
15+ * type TreeNode struct {
16+ * Val int
17+ * Left *TreeNode
18+ * Right *TreeNode
19+ * }
20+ */
21+ func invertTree (root * TreeNode ) * TreeNode {
22+ if root == nil {
23+ return root
24+ }
25+
26+ tmp := invertTree (root .Right )
27+ root .Right = invertTree (root .Left )
28+ root .Left = tmp
29+
30+ return root
31+ }
32+
33+ /*
34+ ํ์ด 2
35+ - ํ์ ๋ฐ๋ณต๋ฌธ์ ์ด์ฉํ์ฌ ํ์ดํ ์ ์์ต๋๋ค
36+
37+ Big O
38+ - N: ๋
ธ๋์ ๊ฐ์
39+ - Time complexity: O(N)
40+ - Space complexity: O(N)
41+ - ํ์ ์ต๋ ํฌ๊ธฐ๋ N / 2 ๋ฅผ ๋์ง ์์ต๋๋ค
42+ ํ์ ์ต๋ ํฌ๊ธฐ๋ ํธ๋ฆฌ์ ๋ชจ๋ ์ธต ์ค์์ ๊ฐ์ฅ ํญ์ด ํฐ ์ธต์ ๋
ธ๋ ์์ ๊ฐ์ต๋๋ค
43+ ๋์ด๊ฐ H์ธ ํธ๋ฆฌ์ ์ต๋ ํญ์ 1. balanced tree์ผ ๋ 2. ๋งจ ์๋ซ ์ธต์ ํญ์ด๊ณ ์ด ๋์ ํญ W๋ 2^(H-1) ์
๋๋ค
44+ ๋์ด๊ฐ H์ธ balanced tree์ ๋
ธ๋ ๊ฐ์๋ 2^H - 1 = N ์ด๋ฏ๋ก ์๋ ๊ด๊ณ๊ฐ ์ฑ๋ฆฝํฉ๋๋ค
45+ N/2 = (2^H - 1) / 2 = 2^(H-1) - 1/2 >= 2^(H-1) = W
46+ ๋ฐ๋ผ์ ๊ณต๊ฐ ๋ณต์ก๋๋ O(N/2) = O(N) ์
๋๋ค
47+ */
48+
49+ /**
50+ * Definition for a binary tree node.
51+ * type TreeNode struct {
52+ * Val int
53+ * Left *TreeNode
54+ * Right *TreeNode
55+ * }
56+ */
57+ func invertTree (root * TreeNode ) * TreeNode {
58+ queue := make ([]* TreeNode , 0 )
59+ queue = append (queue , root )
60+
61+ for len (queue ) > 0 {
62+ node := queue [0 ]
63+ queue = queue [1 :]
64+
65+ if node == nil {
66+ continue
67+ }
68+
69+ tmp := node .Left
70+ node .Left = node .Right
71+ node .Right = tmp
72+
73+ queue = append (queue , node .Left , node .Right )
74+ }
75+
76+ return root
77+ }
You canโt perform that action at this time.
0 commit comments