summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Buetow <git@mx.buetow.org>2020-11-03 09:50:46 +0000
committerPaul Buetow <git@mx.buetow.org>2020-11-03 09:50:46 +0000
commiteebd141f6e7b04518916ad3287b012b83b5a4b5f (patch)
treee840c6817ade10c4cfdd5fd8111faea9ed3eddcc
parentf2b6ebf6ba207f8a9e09088636f7983f67801b81 (diff)
add min and max binary search tree methods
-rw-r--r--set/set.go4
-rw-r--r--set/tree.go45
2 files changed, 42 insertions, 7 deletions
diff --git a/set/set.go b/set/set.go
index 32174bc..29bfad7 100644
--- a/set/set.go
+++ b/set/set.go
@@ -3,8 +3,8 @@ package set
import "fmt"
var (
- NotFound = fmt.Errorf("Could not find entry")
- NotImplemented = fmt.Errorf("Method not implemented")
+ NotFound = fmt.Errorf("could not find entry")
+ NotImplemented = fmt.Errorf("method not implemented")
)
type Set interface {
diff --git a/set/tree.go b/set/tree.go
index 819f83c..3c83f78 100644
--- a/set/tree.go
+++ b/set/tree.go
@@ -65,18 +65,23 @@ func (t *Tree) Del(key int) (int, error) {
return n.val, nil
default:
// I have two childs!
+
+ // Right child has no left child
+ if n.right.left == nil {
+ val := n.val
+ n.right.left = n.left
+ *ptr = n.right
+ return val, nil
+ }
+
return 0, NotImplemented
}
}
-func (t *Tree) min(ptr **node) (**node, *node, error) {
- return nil, nil, NotImplemented
-}
-
func (t *Tree) search(ptr **node, key int) (**node, *node, error) {
n := *ptr
if n == nil {
- return ptr, nil, NotFound
+ return nil, nil, NotFound
}
switch {
@@ -88,3 +93,33 @@ func (t *Tree) search(ptr **node, key int) (**node, *node, error) {
return ptr, n, nil
}
}
+
+func (t *Tree) min(ptr **node, key int) (**node, *node, error) {
+ n := *ptr
+ if n == nil {
+ return nil, nil, NotFound
+ }
+
+ for {
+ if n.left == nil {
+ return ptr, n, nil
+ }
+ ptr = &n.left
+ n = n.left
+ }
+}
+
+func (t *Tree) max(ptr **node, key int) (**node, *node, error) {
+ n := *ptr
+ if n == nil {
+ return nil, nil, NotFound
+ }
+
+ for {
+ if n.right == nil {
+ return ptr, n, nil
+ }
+ ptr = &n.right
+ n = n.right
+ }
+}