~telemachus/algorithms

ref: 7efe7ef5bf2ecd1d8f8111e31064af0296325e03 algorithms/binarysearchtree.go -rw-r--r-- 1.7 KiB
7efe7ef5Peter Aronoff Add Insert and Walk functions 10 months ago
                                                                                
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
109
110
111
package algorithms

type Node struct {
	parent *Node
	left   *Node
	right  *Node
	count  int
	value  int
}

type Tree struct {
	root *Node
	size int
}

type fn func(int)

func NewBST() *Tree {
	return &Tree{}
}

func (t *Tree) Size() int {
	return t.size
}

func (t *Tree) Insert(v int) {
	var prevNode *Node
	currNode := t.root

	// Walk the tree until we find a spot to insert a new node.
	for currNode != nil {
		prevNode = currNode
		switch {
		case v < currNode.value:
			currNode = currNode.left
		case v > currNode.value:
			currNode = currNode.right
		default: // Our value is already present, so we can return early.
			currNode.count++
			t.size++
			return
		}
	}

	// Create a new node, place it, and increase the size of the tree.
	newNode := &Node{value: v, parent: prevNode}
	switch {
	case prevNode == nil:
		t.root = newNode
	case newNode.value < prevNode.value:
		prevNode.left = newNode
	default:
		prevNode.right = newNode
	}
	t.size++
}

func (t *Tree) InOrderWalk(f fn) {
	if t == nil {
		return
	}
	t.root.left.inOrderWalk(f)
	f(t.root.value)
	t.root.right.inOrderWalk(f)
	
}

func (n *Node) inOrderWalk(f fn) {
	if n == nil {
		return
	}
	n.left.inOrderWalk(f)
	f(n.value)
	n.right.inOrderWalk(f)
}

func (t *Tree) PreOrderWalk(f fn) {
	if t == nil {
		return
	}
	f(t.root.value)
	t.root.left.preOrderWalk(f)
	t.root.right.preOrderWalk(f)
}

func (n *Node) preOrderWalk(f fn) {
	if n == nil {
		return
	}
	f(n.value)
	n.left.preOrderWalk(f)
	n.right.preOrderWalk(f)
}

func (t *Tree) PostOrderWalk(f fn) {
	if t == nil {
		return
	}
	t.root.left.postOrderWalk(f)
	t.root.right.postOrderWalk(f)
	f(t.root.value)
}

func (n *Node) postOrderWalk(f fn) {
	if n == nil {
		return
	}
	n.left.postOrderWalk(f)
	n.right.postOrderWalk(f)
	f(n.value)
}