I have written the following code to check if a tree is a Binary search tree. Please help me check the code:
Okay! The code is edited now. This simple solution was suggested by someone in the posts below:
IsValidBST(root,-infinity,infinity);
bool IsValidBST(BinaryNode node, int MIN, int MAX)
{
if(node == null)
return true;
if(node.element > MIN
&& node.element < MAX
&& IsValidBST(node.left,MIN,node.element)
&& IsValidBST(node.right,node.element,MAX))
return true;
else
return false;
}
A Method should only do one thing at a time. Also the way you do things are generally Weird.
I will give you some almost-Java pseudocode. Sorry for that, but I have not touched Java for some Time. I hope it helps. Look at the comments I also did on the Question and I hope you sort it out!
Call your isBST like that :
Internally :
Now : If you want to find the
MinandMaxValues of each Subtree you should use a Container (I used anArrayList) and store a triplet ofNode, Min, Maxwhich represents the root node and the values (obviously).eg.
And a :
Now this is a method which finds the
MinandMaxvalues of a given node:But this returns Values for one Node only, So we gonna use this to find for the Whole Tree:
Using this methods, your call should look like
This is almost Java. It should work with some modification and fix. Find a good OO book, it will help you. Note, that this solution could be broke down into more methods.