You can't change the values of variables in a declarative language. So the answer to your question is that you need to think about the problem a different way. If you describe the problem, rather than the way you would tackle it in Java, then it might be possible to suggest the right approach in XSLT.
However, you're already using recursion so it seems you are part way there. Usually in this kind of problem it's just a question of calculating the values of parameters to pass to the recursive templates.
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference