Check for terminal nodes and refactor