Extract node traversal logic into its own function.