File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 2525package binarytree
2626
2727import (
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.
507542func (n * Node [T ]) AddAttribute (name , value string ) {
You can’t perform that action at this time.
0 commit comments