added a different (and faster) aproach by building the component tree in linear time