Skip to content

Commit 77bebde

Browse files
committed
Solution: Invert Binary Tree
1 parent 3ac0528 commit 77bebde

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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+
}

0 commit comments

Comments
ย (0)