-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.go
108 lines (84 loc) · 1.47 KB
/
demo.go
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func addTree(tree *TreeNode,val int ) *TreeNode {
if tree == nil {
return &TreeNode{Val:val}
}
if tree.Val > val {
tree.Left = addTree(tree.Left,val)
}
if tree.Val <val {
tree.Right = addTree(tree.Right,val)
}
return tree
}
func printT(tree *TreeNode) {
if tree == nil {
return
}
fmt.Println(tree.Val)
printT(tree.Left)
printT(tree.Right)
}
func findMin(t *TreeNode) *TreeNode {
if t.Left == nil {
return t
}
return findMin(t.Left)
}
func delMin(t *TreeNode) *TreeNode {
if t.Left == nil {
newNode := t.Right
t.Right = nil
return newNode
}
t.Left = delMin(t.Left)
return t
}
func delTree(t *TreeNode,val int) *TreeNode {
if t == nil{
return t
}
if t.Val > val {
t.Left = delTree(t.Left,val)
return t
}else if t.Val < val {
t.Right = delTree(t.Right,val)
return t
}else {
if t.Left == nil {
newNode := t.Right
t.Right = nil
return newNode
}else if t.Right == nil {
newNode := t.Left
t.Left = nil
return newNode
} else{
newNode := findMin(t.Right)
newNode.Right = delMin(t.Right)
newNode.Left = t.Left
t.Right,t.Left = nil,nil
return newNode
}
}
}
func main() {
t := &TreeNode{Val:33}
t = addTree(t,41)
t = addTree(t,50)
t = addTree(t,12)
t = addTree(t,20)
t = addTree(t,6)
t = addTree(t,34)
t = addTree(t,43)
t = addTree(t,60)
printT(t)
fmt.Println("..........")
printT(delTree(t,41))
}