Adding tree cache to avoid generating the tree more than once.