A binary tree is ordered if all its children are under the left branch that the data of the root and branch of the right age and, in turn, binary trees of the left and right branches are also sorted. Write the procedure (ordered-btree? btree) receiving a binary tree as argument and returns True if ordered and false if not.
How can I do this?
There are several ways to solve this problem. I'll assume that there are no repeated elements in the tree and that you have written helper procedures for testing whether a tree is empty, whether it's a leaf (that is, both left and right subtrees are empty), for returning the left and right subtrees, the value in each node, the minimum value in a tree and the maximum - these should be trivial to write. The first implementation follows closely the recursive definition mentioned in the question, but it's not very efficient:
A second approach would be to obtain a list of the tree's values using an in-order traversal, and then check if the returned list is sorted. This is a more efficient solution, I'll outline it - once again assuming that the proper helper procedures are in place:
You make a recursive procedure that returns
true
for empty or leaf node,false
if either children are wrong order. A default case (if none of the previous hit) the result is the recursion ofordered-btree?
on both children in anand
form. eg.(and (ordered-btree? left-child) (ordered-btree? right-child))
Notice that
true
andfalse
is not standard Scheme.#t
and#f
is.Edit since Óscar posted code I'll post my buffer as well:
How it works is that whenever you process the left child you know you should never have any higher values than the current node. For the right child you should never encounter a lower value than the current node.
maxv
andminv
narrows down to the only valid range as you traverse. As a starting point I use negative and positive infinitive making the root node have any value.