Calculating nonterminal and intermediate node ids