Recursion is your friend!
pseudo code:
numOfTrees(n): return trees(n).size(); trees(n): if (n==1) return new list of single node; big_trees = new empty list; for (small_tree : trees(n-1)) for (big_tree : addSingleNode(tree)) big_trees.insert(big_tree); return big_trees; addSingleNode(tree): trees = new empty list; for (leaf : getLeaves(tree)) { trees.insert(tree.clone().addLeftChild(leaf, node)); trees.insert(tree.clone().addRightChild(leaf, node)); } return trees;
getLeaves () is implementation dependent, if you have a linked list with all the sheets then it will be fast, otherwise you may need to traverse the tree checking the leaves (which is O (n) in_order).
memory is not very efficient, but it solves the problem by simple recursion, where at each stage I take trees and look through all the leaves and add a new node in all possible ways.
davin source share