Refactor Java tree traversal