I think you would address them by their title if you were writing to them in their official capacity, so if I wanted to write to President Trump to try to change his approach to something, I would write 'Dear President Trump' (or perhaps 'Dear Mr President') even though I'm not a US citizen.
But as well as it being about the official capacity in which you are writing, I think it's also to do with 'rank/importance' and partly to do with tradition.
So I can see someone writing formally to the headteacher at their child's school starting 'Dear headmaster/headmistress' (though personally I wouldn't), but surely no one would start a letter to their child's teacher ' Dear teacher'?
I have just dug out and consulted an 1982 edition copy of Debrett's 'Etiquette and Modern Manners' which has a whole section called 'Correct forms of address'. That confirms that letters to ministers should start 'Dear Prime Minister/Home Secretary/Secretary of State', and that letters to MPs should start eg 'Dear Mr X'.
It also has all sorts of info on how to address law officers (eg the Lord Chief Justice gets 'Dear Lord Chief Justice' but QCs simply get eg 'Dear Mr X'); Clergymen (eg in the CofE it's eg 'Dear Bishop', Dear Archdeacon' etc but vicars just get 'Dear Mr X' or 'Dear Father X'), the armed services, the police, doctors and dentists (plus the Royal family and aristocracy).
There is nothing on how to address those in the education sector, unfortunately!