private bool Reduce(Stack <KeyValuePair <string, BinaryTree <string> > > parseStack, bool reduceRoot) { IList <KeyValuePair <string, BinaryTree <string> > > stackElements = new List <KeyValuePair <string, BinaryTree <string> > >(); while (parseStack.Count > 0) { var peek = parseStack.Pop(); stackElements.Insert(0, peek); var stringElements = string.Join(string.Empty, stackElements.Select(x => x.Key)); if (CanReduce(stringElements, reduceRoot, out var grammarRule)) { var replacement = grammarRule.Symbol; var tree = new BinaryTree <string>(grammarRule.Symbol); foreach (var element in stackElements) { if (_excludedFromTree.All(x => element.Key.Trim() != x)) { tree.AddChild(element.Value); } } parseStack.Push(new KeyValuePair <string, BinaryTree <string> >(replacement, tree)); return(true); } } foreach (var item in stackElements) { parseStack.Push(item); } return(false); }