Search code examples
syntaxbnf

How to write the BNF for this tree-related operation?


We have a tree like this:

enter image description here

We can convert it to a dotstring representation, i.e.,

Such a tree can be represented by the preorder sequence of its nodes in which dots (.) are inserted where an empty subtree (nil) is encountered during the tree traversal.

So we can convert the tree in the picture to 'abd..e..c.fg...'.

If I am about to write a function to do this conversion, what's the BNF or syntax diagrams of it?


Solution

  • It's not clear what you're asking. If you think of the string as a sentence in a language and the tree as an AST for a parse, maybe the following BNF would be right:

    tree ::= empty | node
    empty ::= '.'
    node ::= letter tree tree
    letter ::= 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | ...