problem team player leave and other player join

Options

this system even works, but his problem is if a player leaves the room and enter another there the player and added in the team with more player

I wanted to balance the teams every time a player enters the match
//TEAM Random ================================
for (int i = 0; i < PhotonNetwork.room.PlayerCount; i++)
{
if (i >= maxPlayerRoom / 2)
{
PhotonNetwork.player.SetTeam(PunTeams.Team.red);


}
else
{
PhotonNetwork.player.SetTeam(PunTeams.Team.blue);

}

}