forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobzva.go
More file actions
77 lines (65 loc) Β· 1.71 KB
/
obzva.go
File metadata and controls
77 lines (65 loc) Β· 1.71 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
72
73
74
75
76
77
/*
νμ΄ 1
- ν¨μμ μ¬κ·νΈμΆμ μ΄μ©ν΄μ νμ΄ν μ μμ΅λλ€
Big O
- N: λ
Έλμ κ°μ
- H: νΈλ¦¬μ λμ΄
- Time complexity: O(N)
- Space complexity: O(H) (logN <= H <= N)
- μ¬κ· νΈμΆ μ€νμ μ΅λ κΉμ΄λ νΈλ¦¬μ λμ΄μ λΉλ‘νμ¬ μ¦κ°ν©λλ€
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return root
}
tmp := invertTree(root.Right)
root.Right = invertTree(root.Left)
root.Left = tmp
return root
}
/*
νμ΄ 2
- νμ λ°λ³΅λ¬Έμ μ΄μ©νμ¬ νμ΄ν μ μμ΅λλ€
Big O
- N: λ
Έλμ κ°μ
- Time complexity: O(N)
- Space complexity: O(N)
- νμ μ΅λ ν¬κΈ°λ N / 2 λ₯Ό λμ§ μμ΅λλ€
νμ μ΅λ ν¬κΈ°λ νΈλ¦¬μ λͺ¨λ μΈ΅ μ€μμ κ°μ₯ νμ΄ ν° μΈ΅μ λ
Έλ μμ κ°μ΅λλ€
λμ΄κ° HμΈ νΈλ¦¬μ μ΅λ νμ 1. balanced treeμΌ λ 2. 맨 μλ« μΈ΅μ νμ΄κ³ μ΄ λμ ν Wλ 2^(H-1) μ
λλ€
λμ΄κ° HμΈ balanced treeμ λ
Έλ κ°μλ 2^H - 1 = N μ΄λ―λ‘ μλ κ΄κ³κ° μ±λ¦½ν©λλ€
N/2 = (2^H - 1) / 2 = 2^(H-1) - 1/2 >= 2^(H-1) = W
λ°λΌμ κ³΅κ° λ³΅μ‘λλ O(N/2) = O(N) μ
λλ€
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
queue := make([]*TreeNode, 0)
queue = append(queue, root)
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if node == nil {
continue
}
tmp := node.Left
node.Left = node.Right
node.Right = tmp
queue = append(queue, node.Left, node.Right)
}
return root
}