-
Notifications
You must be signed in to change notification settings - Fork 0
/
binaryTree.go
88 lines (74 loc) · 1.55 KB
/
binaryTree.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
package dataStruct
import "fmt"
type BinaryTreeNode struct {
Val int
left *BinaryTreeNode
right *BinaryTreeNode
}
type BinaryTree struct {
Root *BinaryTreeNode
}
func NewBinaryTree(v int) *BinaryTree {
tree := &BinaryTree{}
tree.Root = &BinaryTreeNode{Val: v}
return tree
}
func (n *BinaryTreeNode) AddNode(v int) *BinaryTreeNode {
if n.Val > v {
if n.left == nil {
n.left = &BinaryTreeNode{Val: v}
return n.left
} else {
return n.left.AddNode(v)
}
} else {
if n.right == nil {
n.right = &BinaryTreeNode{Val: v}
return n.right
} else {
return n.right.AddNode(v)
}
}
}
type depthNode struct {
depth int
node *BinaryTreeNode
}
func (t *BinaryTree) Print() {
q := []depthNode{}
q = append(q, depthNode{depth: 0, node: t.Root})
currentDepth := 0
for len(q) > 0 {
var first depthNode
first, q = q[0], q[1:]
if first.depth != currentDepth {
fmt.Println()
currentDepth = first.depth
}
fmt.Print(first.node.Val, " ")
if first.node.left != nil {
q = append(q, depthNode{depth: currentDepth + 1, node: first.node.left})
}
if first.node.right != nil {
q = append(q, depthNode{depth: currentDepth + 1, node: first.node.right})
}
}
}
func (t *BinaryTree) Search(v int) (bool, int) {
return t.Root.Search(v, 1)
}
func (n *BinaryTreeNode) Search(v int, cnt int) (bool, int) {
if n.Val == v {
return true, cnt
} else if n.Val > v {
if n.left != nil {
return n.left.Search(v, cnt+1)
}
return false, cnt
} else {
if n.right != nil {
return n.right.Search(v, cnt+1)
}
return false, cnt
}
}