Tree Traversal and Stack
A grammar can be written to describe the syntax of the language of balanced parentheses:
S → ( S )
S → [ S ]
S → { S }
S → S S
S → ε
This grammar describes a balanced parenthesis string as a tree. As we check the syntax of a string, the stack always contains the unbalanced symbols between the current symbol and the root of the tree.