Isn't this easier to solve by walking the tree recursively?