Given a simple binary tree, how can we prove that tree is a binary search tree? When we traverse a binary tree, how do we know if the node we are on is the left or right child of its parent? I came up with one solution where i would pass some flag in recursive function call which could keep track of whether the node is left or right child of its parent as well as we need one parent node pointer through which we can compare :-
if(flag == 'L' && node->value < node->parent->value)
then continue recursion;
else{
print "not a binary search tree"
exit;
}
In the same way one if condition is needed for R. Apart from this can you think any other efficient way?
Thanks in advance 🙂
I would just check:
currentNode.Left.max() < currentNode.ValueandcurrentNode.Left.isBinarySearchTree(). If both are fulfilled, it’s a binary search tree.Edit:
The above does traverse the left tree twice (once for the
max()and once forisBinarySearchTree. However, it can be done using just one traversal:Store the minimum and maximum element in your tree class. Updates, etc. of course can be done in O(1) space and time.
Then, instead of using
max(), make a methodisInRange(m,M), that checks, whether a (sub)tree contains only elements in the range(m,m+1,...,M).Define
isInRange(m,M)as follows:Then, the initial call would be
root.isInRange(globalmin, globalmax).Didn’t test it so I don’t know if it matters in performance.