When you take a course on Data Structures and Formal Language in the same semester 😂. This project focuses on validating expressions that define a tree using a context-free grammar, and automatically contructing this tree in the computer memory. It also outputs the inorder, postorder and preorder traversals of the tree.
Nodes are denoted by single characters and parentheses, (
and )
, are used to mark the beginning and ending of subtrees, respectively.
Suppose we have the following tree
A
├── B
│ ├── D
│ └── E
├── C
│ ├── F
│ │ ├── K
│ │ └── L
│ └── G
The corresponding expression will be A(B(DE)C(F(KL)G))
- G = (VN, VT, S, P)
- VN (Non-terminal symbols): { S, A, B, C }
- VT (Terminal symbols): { x, (, ) }
- S: Start symbol
- P (Production Rules):
S → x | x(xA) A → λ | xA | (B)C C → λ | x | xA B → x | xA
In this context, x
is any single character that is not (
or )
and represents a node.
The set of valid expressions L(G)
includes expressions E
that meet the following conditions:
- Symbol Check: Every character in
E
must bex
,(
, or)
. - Starting Node: The first character of
E
must bex
. - Balanced Parentheses: The number of open parentheses
(
must equal the number of closed parentheses)
. - Missing Parent: The sequences
)(
and((
must not appear inE
. - Empty Subtree: The sequence
()
must not appear inE
.
- Validation Logic: Uses context-free grammar to validate tree-defining expressions.
- Error Handling: Ensures expressions have balanced parentheses and follow specified sequence rules.
- Algorithm Explanation: Detailed descriptions of the grammar and validation steps.