Definition (parse tree)
Let $G = (Σ, V, P, S)$ be a context-free grammar, and $A\in V$ be a variable.
A pair $\mathbf{T} = (T,l)$ is a $G$-parse tree starting from $A$ if $T$ is a finite finitely branching tree and $l: T \to Ω$ satisfying
-
$l(ε) = A$;
-
if $l(t) \in Σ$, then $t$ is a leaf in $T$; and
-
if $l(t) \in V$ and $t$ is $n+1$-branching ($n\in \N$, i.e. $t$ is not a leaf), then there is a rule $l(t) \to x_0 x_1 \ldots x_n \in P$ such that $l(tk) = x_k$ for all $k=0,1,\ldots,n$.
Write $σ_\mathbf{T} = l(t_0) \ldots l(t_m)$ for the string parsed by $\mathbf{T}$, where $l_0 < t_1 < \ldots < t_m$ are the leaves of $\mathbf{T}$ totally-ordered by the left-to-right order.
For $t\in T$ not a leaf, define the subtree at $t$ by $\mathbf{T}_t = (T_t, l_t)$ where $T_t = \sb{s\in \N^\ast}{ts\in T}$ and $l_t(s) = l(ts)$.
-
$\mathbf{T}_t$ is a $G$-parse tree starting from $l(t).$
-
Under the left-to-right ordering, the leaves of $\mathbf{T}_t$ are a consecutive sequence of the leaves of $\mathbf{T}$. Therefore $σ_\mathbf{T} = u σ_{\mathbf{T}_t} v$, where $u\in \mathbb{W}$ corresponds to all leaves of $\mathbf{T}$ to the left of leaves of $\mathbf{T}_t$, and $w\in \mathbb{W}$ corresponds to all leaves of $\mathbf{T}$ to the right of leaves of $\mathbf{T}_t$.
If $\mathbf{T}$ and $\mathbf{T}'$ are $G$-parse trees, $t\in T$ with $l(t) = A$ and $\mathbf{T}'$ starts from $A$, then we can graft $\mathbf{T}'$ into $\mathbf{T}$: define $\mathrm{graft}(\mathbf{T}, t, \mathbf{T}') = (T^\star, l^\star)$ where $T^\star = \sb{s\in T}{t\not\subseteq s} \cup \sb{ts}{s\in T'}$ and $$ \begin{align*} l^\star(s) = \begin{cases} l(s), &\text{if } t\not\subseteq s, \\ l'(u), &\text{if } s = tu \text{ for some $u\in T'$}. \end{cases} \end{align*} $$
-
Grafting corresponds to removing the subword $σ_{\mathbf{T}_t}$ from $σ_{\mathbf{T}}$ and replacing it with $σ_{\mathbf{T}'}$.