Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a BST is valid?

How can I check if a BST is a valid one, given its definition and using a generalized version of fold for BST?

data(Ord a, Show a, Read  a) => BST a = Void | Node {
    val :: a,
    left, right :: BST a
} deriving (Eq,  Ord,  Read, Show)


fold :: (Read a, Show a, Ord a) => (a -> b -> b ->  b) -> b -> BST a -> b
fold _ z Void         = z
fold f z (Node x l r) = f x (fold f z l) (fold f z r)

The idea is to check that a node value is greater then all values in left-subtree and smaller than all values in its right-subtree. This must be True for all nodes in the tree. A function bstList simply output the list of (ordered) values in the BST.

Of course something like this won't work:

--isBST :: (Read a, Show a, Ord a) => BST a -> Bool
isBST t = fold (\x l r -> all (<x) (bstList l) && all (>x) (bstList r)) (True) t

because, for example, applying the fold function to the node 19 ends up all (<19) (bstList True) && all (>19) (bstList True).

a BST

like image 963
gremo Avatar asked Feb 12 '11 22:02

gremo


People also ask

How can I search a BST number?

Let's say we want to search for the number, we start at the root, and then we compare the value to be searched with the value of the root, if it's equal we are done with the search if it's smaller we know that we need to go to the left subtree because in a binary search tree all the elements in the left subtree are ...

Is a single node a valid BST?

Inorder traversal of a single node will always return a sorted order, and a single node will always be a binary search tree.

Is an empty BST a valid BST?

Yes both conditions are true. For a binary tree, each node can have zero, one, or two children. If a tree has only a root node and no other node then it is called a NULL tree.


1 Answers

Your problem seems to be that you lose information because your function only returns a boolean when it examines the left and right subtrees. So change it to also return the minimum and maximum values of the subtrees. (This is probably more efficient as well, since you don't need to used bslist to check all elements anymore)

And make a wrapper function to ignore these "auxiliary" values after you are done, of course.

like image 163
hugomg Avatar answered Oct 26 '22 16:10

hugomg