As a partial answer, you can start by eliminating most of the repetition in your code. For example, you don't need to special-case the lookup() function for the three different node types. You could instead write something like this.