print $ merge (inorder treeA) (inorder treeB)
what's the problem?
(notice, the above is actual Haskell code which actually runs and performs the task). inorder
is trivial to implement with recursion. merge
is a nearly-standard feature, merging its two argument ordered (non-decreasing) lists, producing an ordered output list, keeping the duplicates.
Because of lazy evaluation and garbage collection, the lists are not actually created - at most one produced element is retained for each tree, and is discarded when the next one is produced, in effect creating iterators for the traversals (each with its own internal state).
Here's the solution (if your language does not support the above, or the equivalent yield
mechanism, or the explicit continuations of Scheme which allow to switch between two contexts deep inside control stack each (thus making it possible to have "two recursions" in parallel, as in the above)):
They don't say anything about time complexity, so we can do a recursive traversal of 1st tree, and traverse the 2nd tree anew, for each node of the 1st tree - while saving previous
value on 1st. So, we have two consecutive values on 1st tree, and print all values from 2nd tree between them, with fresh recursive traversal, restarting from the top of the 2nd tree for each new pair of values from the 1st tree.