Skip to content

Commit cb550a1

Browse files
committed
Commit IsBinarySearchTree() test predicate
1 parent 70227c2 commit cb550a1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

binarytree.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
package binarytree
2626

2727
import (
28+
"errors"
2829
"fmt"
2930
"io"
3031
"strconv"
@@ -502,6 +503,40 @@ func (n *Node[T]) IsPerfectTree() bool {
502503
return n.IsFullTree() && n.IsCompleteTree()
503504
}
504505

506+
// errNotBst is returned by a walking function when a tree being
507+
// walked is detected to not be a BST.
508+
var errNotBst = errors.New("not a binary search tree")
509+
510+
// IsBinarySearchTree returns true, if the tree is a Binary Search
511+
// Tree (BST).
512+
func (n *Node[T]) IsBinarySearchTree(comparator ComparatorFunc[T]) bool {
513+
if n.IsLeafNode() {
514+
return true
515+
}
516+
517+
// Use errNotBst to signal a condition to stop walking the
518+
// tree as soon as we know this is a not a BST.
519+
var last *Node[T]
520+
walkFunc := func(curr *Node[T]) error {
521+
if last != nil && comparator(last.Value, curr.Value) > 0 {
522+
return errNotBst
523+
}
524+
last = curr
525+
526+
return nil
527+
}
528+
529+
err := n.WalkInOrder(walkFunc)
530+
switch {
531+
case err == errNotBst:
532+
return false
533+
case err != nil:
534+
panic(err)
535+
default:
536+
return true
537+
}
538+
}
539+
505540
// AddAttribute associates an attribute with the node, which will be
506541
// used when generating the Dot representation of the tree.
507542
func (n *Node[T]) AddAttribute(name, value string) {

0 commit comments

Comments
 (0)