Refactor script tree traversal