Rewrite mergeTerms using generic tree-traversal