Skip to content

Commit d17480f

Browse files
committed
Commit tests for IsBinarySearchTree() predicate
1 parent 70a63b3 commit d17480f

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

binarytree_test.go

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,113 @@ func TestIsPerfectTree(t *testing.T) {
746746
}
747747
}
748748

749+
func TestIsBinarySearchTree(t *testing.T) {
750+
// A valid BST
751+
//
752+
// 2
753+
// / \
754+
// 1 3
755+
//
756+
root := binarytree.NewNode(2)
757+
root.InsertLeft(1)
758+
root.InsertRight(3)
759+
760+
if !root.IsBinarySearchTree(binarytree.IntComparator) {
761+
t.Fatal("tree should be BST")
762+
}
763+
764+
// Invalid BST
765+
//
766+
// 1
767+
// / \
768+
// 2 3
769+
//
770+
root = binarytree.NewNode(1)
771+
root.InsertLeft(2)
772+
root.InsertRight(3)
773+
774+
if root.IsBinarySearchTree(binarytree.IntComparator) {
775+
t.Fatal("tree should not be BST")
776+
}
777+
778+
// Invalid BST
779+
//
780+
// 1
781+
// / \
782+
// 2 3
783+
// /
784+
// 4
785+
//
786+
root = binarytree.NewNode(1)
787+
root.InsertRight(3)
788+
two := root.InsertLeft(2)
789+
two.InsertLeft(4)
790+
791+
if root.IsBinarySearchTree(binarytree.IntComparator) {
792+
t.Fatal("tree should not be BST")
793+
}
794+
795+
// A valid BST
796+
//
797+
// ______8
798+
// / \
799+
// 3__ 10___
800+
// / \ \
801+
// 1 6 _14
802+
// / \ /
803+
// 4 7 13
804+
//
805+
root = binarytree.NewNode(8)
806+
three := root.InsertLeft(3)
807+
three.InsertLeft(1)
808+
six := three.InsertRight(6)
809+
six.InsertLeft(4)
810+
six.InsertRight(7)
811+
ten := root.InsertRight(10)
812+
fourteen := ten.InsertRight(14)
813+
fourteen.InsertLeft(13)
814+
815+
if !root.IsBinarySearchTree(binarytree.IntComparator) {
816+
t.Fatal("tree should be BST")
817+
}
818+
819+
// A tree with a single root node is a valid BST
820+
root = binarytree.NewNode(1)
821+
if !root.IsBinarySearchTree(binarytree.IntComparator) {
822+
t.Fatal("tree should be BST")
823+
}
824+
825+
// A valid BST
826+
//
827+
// B
828+
// / \
829+
// A C
830+
//
831+
str_root := binarytree.NewNode("B")
832+
str_root.InsertLeft("A")
833+
str_root.InsertRight("C")
834+
835+
if !str_root.IsBinarySearchTree(binarytree.StringComparator) {
836+
t.Fatal("tree should be BST")
837+
}
838+
839+
// Invalid BST
840+
//
841+
// A
842+
// / \
843+
// B C
844+
// /
845+
// D
846+
str_root = binarytree.NewNode("A")
847+
str_root.InsertRight("C")
848+
b := str_root.InsertLeft("B")
849+
b.InsertLeft("D")
850+
851+
if str_root.IsBinarySearchTree(binarytree.StringComparator) {
852+
t.Fatal("tree should not be BST")
853+
}
854+
}
855+
749856
func TestNodeAttributes(t *testing.T) {
750857
root := binarytree.NewNode(1)
751858

0 commit comments

Comments
 (0)