optimize traversePre with a stack-based stack