Iran and Saudi Arabia have agreed to re-establish diplomatic relations and reopen embassies after talks in Beijing between officials from the two rival Middle East powers.