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;
}