Home > Articles, Compilers & Interpreters > Implementation of an algorithm for creating a syntax tree.

Implementation of an algorithm for creating a syntax tree.

The following program creates the syntax tree of a mathematical expression in prefix notation. For simplicity, we assume that the terms of the expression are individual characters (digits). Each time the recursive function parse() is called, a new node is created, whose value is the next character of the expression. If the value is a term (digit), we return the new node. However, if it is an operator, we set the left and right pointers to point the tree made (recursively) for the two operands.

You should know that the implementation of the algorithm does not take into account issues of data input validation or proper management of dynamic memory (e.g. avoiding memory leaks) because it is only necessary to highlight the logic of the algorithm.

char *a = "+ * 4 3 2"; int i = 0;

struct node {
  Item item; node *l, *r; 

  node (Item x) {
    item = x; l = 0; r = 0;
  }
};

typedef node *link;

link
parse () {
  char t = a[i++]; link x = new node (t);

  if ((t == '+') || (t == '*')) {
    x->l = parse (); x->r = parse ();
  }

  return x;
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: