Refactored common traversal code into one function.