Skip to content

Commit 5724286

Browse files
committed
implement binary search tree
1 parent 216e24a commit 5724286

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Binary search tree
2+
// https://en.wikipedia.org/wiki/Binary_search_tree
3+
4+
package binarySearchTree
5+
6+
// package main
7+
8+
import "fmt"
9+
10+
type node struct {
11+
val int
12+
left *node
13+
right *node
14+
}
15+
16+
type tree struct {
17+
root *node
18+
}
19+
20+
func newNode(val int) *node {
21+
return &node{val, nil, nil}
22+
}
23+
24+
func inorder(n *node) {
25+
if n != nil {
26+
inorder(n.left)
27+
fmt.Print(n.val, " ")
28+
inorder(n.right)
29+
}
30+
}
31+
32+
func insert(root *node, val int) *node {
33+
if root == nil {
34+
return newNode(val)
35+
}
36+
if val < root.val {
37+
root.left = insert(root.left, val)
38+
} else {
39+
root.right = insert(root.right, val)
40+
}
41+
return root
42+
}
43+
44+
func inorderSuccessor(root *node) *node {
45+
cur := root
46+
for cur.left != nil {
47+
cur = cur.left
48+
}
49+
return cur
50+
}
51+
52+
func bst_delete(root *node, val int) *node {
53+
if root == nil {
54+
return nil
55+
}
56+
if val < root.val {
57+
root.left = bst_delete(root.left, val)
58+
} else if val > root.val {
59+
root.right = bst_delete(root.right, val)
60+
} else {
61+
// this is the node to delete
62+
63+
// node with one child
64+
if root.left == nil {
65+
root = root.right
66+
} else if root.right == nil {
67+
root = root.left
68+
} else {
69+
// node with two children
70+
d := inorderSuccessor(root)
71+
root.val = d.val
72+
root.right = bst_delete(root.right, d.val)
73+
}
74+
}
75+
return root
76+
}
77+
78+
/*
79+
func main() {
80+
t := &tree{nil}
81+
inorder(t.root)
82+
t.root = insert(t.root, 10)
83+
t.root = insert(t.root, 20)
84+
t.root = insert(t.root, 15)
85+
t.root = insert(t.root, 30)
86+
inorder(t.root)
87+
fmt.Print("\n")
88+
t.root = bst_delete(t.root, 10)
89+
inorder(t.root)
90+
fmt.Print("\n")
91+
t.root = bst_delete(t.root, 30)
92+
inorder(t.root)
93+
fmt.Print("\n")
94+
t.root = bst_delete(t.root, 15)
95+
inorder(t.root)
96+
fmt.Print("\n")
97+
t.root = bst_delete(t.root, 20)
98+
inorder(t.root)
99+
fmt.Print("\n")
100+
}
101+
*/

0 commit comments

Comments
 (0)