I have 2 binary search trees T1 and T2 with same number of nodes n >= 1. For each node P we have LEFT(P) and RIGHT(P) for links between nodes and KEY(P) for value off the node. The root of T1 is R1 and root of T2 is R2. I need a linear algorithm which will determine values which are found both in T1 and in T2.
My idea until now is to do an inorder traversal of T1 and search in T2 for current element, like this:
inorder(node)
if node is not NULL
inorder(LEFT(node))
if find(KEY(node), R2)
print KEY(node)
inorder(RIGHT(node))
Where find(KEY(node), R2) implement a binary search for KEY(node) in tree T2.
Is this the correct solution? Is this a linear algorithm? (I know traversal is O(n) complexity). Or, there is another method to intersect 2 binary search trees?
Thanks!