refactor tree traversal