Comparing two binary trees (is element A of Tree1 also element of Tree2?)
Hello
Is there any "classic" algorithm that searches a given tree to find if it share elements (value) with other trees ?
Something like traversing Tree1 and, for each element/node, check all of Tree2's nodes and compare would probably work... although it seams "heavy".
Thanks
[304 byte] By [
WillTrya] at [2007-10-2 2:09:04]

It depends on what you mean by equal. Two binary trees built using the same algorithm. If the nodes were inserted into the trees in different orders then the trees will likely have different structures but a ordered traversal will resolve this issue. Just get an iterator over each tree and compare elements .
public boolean compare(Tree a, Tree b) {
Iterator ita = a.iterator();
Iterator itb = b.iterator();
boolean result = (a.size() == b.size());
while(ita.hasNext() && itb.hasNext() && result) {
if(!ita.next().equals(itb.next())) {
result = false;
}
}
return result;
}
Other trees can be compared using variations on these themes. Trees (for gui display) with n unsorted nodes per leaf can be comapred by sorting the nodes and comparing them at each level.
So basically it depends on the tree and in some cases they way the tree is constructed.
matfud