The hostage-taker was detained by police officers from the elite GIPN force, who slipped into the school as the children were being brought lunch, Education Minister Luc Chatel said.
"We brought in meals, and it was at that moment that the GIPN was able to intervene, separate the children, free them and apprehend the hostage-taker," he said in televised comments from the scene.
French television showed a wide-eyed girl being draped in a green blanket and carried away from the school. Police and worried families had surrounded the Charles Fourier preschool in Planoise, a neighborhood of housing projects with a big immigrant population on the western edge of Besancon.
The hostage-taker's motives were unclear. Described by officials as depressive and known to the neighborhood, the teen appeared to be gentle with his preschool hostages.
He let several of the children go join their parents outside, and he did not threaten those who remained, even allowing them to go to the bathroom, Chatel said.
Besancon Mayor Jean-Louis Fousseret said the teen had been treated for depression but had not taken his medication in recent days. The mayor did not confirm reports that the youth had requested a gun to commit suicide.
The hostage-taker initially seized a class of 20 children but released 14 throughout the morning, including one who "more or less escaped," Fousseret said.
Five or six children and the teacher were believed to be still in the preschool when the officers entered at lunchtime, he said on i-tele television.
The masked gendarmes pointed their firearms at the school's windows and doors as they entered, in images shown on French TV. They were in contact by telephone with the hostage-taker before the last group of children was released.
Families huddled around the school, with children bundled against the cold. Emergency workers draped a blanket over one woman's shoulders as she wept.
Pupils were still inside the adjacent elementary school while the events unfolded.
"It's a bit traumatizing. ... We are just across from where everything is happening," principal Alain Lietta told the AP. The schools' entrances are about 60 meters (yards) apart. Normally some children go home at lunch but "today, this poses a problem," he said.
President Nicolas Sarkozy welcomed the "happy ending" to the hostage-taking. In a statement, he expressed support for the teacher taken hostage and the school personnel, and praised the "sang-froid, professionalism and determination" of the police and gendarmes who helped free the children.
Sarkozy first vaulted into France's national consciousness during a similar hostage-taking in 1993 in the posh Paris suburb of Neuilly-sur-Seine, where as mayor he helped free nursery school children and a teacher who had been taken hostage by a masked gunman.