Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 3 · syllabusAsked 2× in KTU papersLesson live

Expression trees

Operators inside, operands at the leaves: build the tree for any expression and read off prefix, infix and postfix.

Syllabus says: “Expression Trees”

On this page · 12 sections
ormakkurippu ✎
Never-forget card

The operator applied LAST is the ROOT. Split the expression at that operator and repeat on each side.

Picture it

Like a cricket tournament bracket: the final (the last operation) sits at the top, the semi-finals below it, and the teams (operands) at the bottom.

Write this in the exam

An expression tree is a binary tree whose leaves are operands and whose internal nodes are operators; its inorder, preorder and postorder traversals give the infix, prefix and postfix forms.

What you will be able to do

  • Construct an expression tree for a given infix expression (Nov 2025 Q6, model paper Q13b).
  • Build a tree from postfix with a stack.
  • Evaluate an expression tree.

How to construct one by hand

  1. Add brackets according to precedence and associativity.
  2. The operator outside all brackets that is applied last becomes the root.
  3. Its left operand becomes the left subtree and its right operand the right subtree — repeat.

From postfix with a stack

algorithm
Algorithm BuildTree(postfix)
1. for each symbol s from left to right do
2.     if s is an operand then push(newNode(s))
3.     else                              // operator
4.         r ← pop();  l ← pop()
5.         push(newNode(s, l, r))
6. return pop()                          // the root

Algorithm Eval(t)
1. if t is a leaf then return value(t)
2. return Eval(t→left)  op(t)  Eval(t→right)

Worked example

Bracketed fully: (((A + (B*C)) − D) − (E*F)) − (G − (H/I)). The last − is the root.

A+B*C-D-E*F-G-H/I
Expression tree. Postorder: A B C * + D − E F * − G H I / − −.

Model paper Q13b: (a+b*c/d) + ((e*f+g)*h)

a+b*c/d+e*f+g*h
b*c/d groups as (b*c)/d. Postorder: a b c * d / + e f * g + h * +.

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

C implementation

expression_tree.ctested ✓ 400/400 cases
C
/* Expression tree from an infix expression — KTU PCCST303, Module 3 (KTU Nov 2025 Q6, model Q13b)
 * Step 1: infix -> postfix with an operator stack (^ is right-associative, highest).
 * Step 2: scan the postfix: an operand becomes a one-node tree; an operator pops the
 *         right subtree, then the left subtree, and becomes their parent.
 * Then preorder = prefix form, postorder = postfix form.
 * Input : one valid infix expression per line (letters, whole numbers, + - * / % ^ ( )).
 * Output: "PREFIX: ..." and "POSTFIX: ..." for each line.                                */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAXTOK 128
struct node {
    char tok[12];
    struct node *left, *right;
};

int prec(char c) { return c == '^' ? 3 : (c == '*' || c == '/' || c == '%') ? 2 : (c == '+' || c == '-') ? 1 : 0; }
int isOp(const char *t) { return t[1] == '\0' && prec(t[0]) > 0; }

/* split into tokens: numbers, single letters, operators and brackets */
int tokenize(const char *s, char tok[][12]) {
    int n = 0;
    while (*s && n < MAXTOK) {
        if (isspace((unsigned char)*s)) { s++; continue; }
        if (isdigit((unsigned char)*s)) {
            int k = 0;
            while (*s == '0' && isdigit((unsigned char)s[1])) s++;   /* "007" is 7 */
            while (isdigit((unsigned char)*s) && k < 10) tok[n][k++] = *s++;
            tok[n++][k] = '\0';
        } else { tok[n][0] = *s++; tok[n++][1] = '\0'; }
    }
    return n;
}

int toPostfix(char in[][12], int n, char out[][12]) {
    char stack[MAXTOK];
    int top = -1, k = 0, i;
    for (i = 0; i < n; i++) {
        char c = in[i][0];
        if (isalnum((unsigned char)c)) strcpy(out[k++], in[i]);
        else if (c == '(') stack[++top] = c;
        else if (c == ')') {
            while (top >= 0 && stack[top] != '(') { out[k][0] = stack[top--]; out[k++][1] = '\0'; }
            top--;                                     /* discard '(' */
        } else {
            /* pop while the stack top has higher precedence, or equal and left-associative */
            while (top >= 0 && stack[top] != '(' && (prec(stack[top]) > prec(c) || (prec(stack[top]) == prec(c) && c != '^'))) {
                out[k][0] = stack[top--]; out[k++][1] = '\0';
            }
            stack[++top] = c;
        }
    }
    while (top >= 0) { out[k][0] = stack[top--]; out[k++][1] = '\0'; }
    return k;
}

struct node *build(char post[][12], int n) {
    struct node *stack[MAXTOK];
    int top = -1, i;
    for (i = 0; i < n; i++) {
        struct node *t = malloc(sizeof *t);
        if (t == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
        strcpy(t->tok, post[i]);
        t->left = t->right = NULL;
        if (isOp(post[i])) { t->right = stack[top--]; t->left = stack[top--]; }  /* right first! */
        stack[++top] = t;
    }
    return stack[top];
}

void preorder(struct node *t)  { if (t) { printf(" %s", t->tok); preorder(t->left); preorder(t->right); } }
void postorder(struct node *t) { if (t) { postorder(t->left); postorder(t->right); printf(" %s", t->tok); } }
void freeTree(struct node *t)  { if (t) { freeTree(t->left); freeTree(t->right); free(t); } }

int main(void) {
    char line[512], in[MAXTOK][12], post[MAXTOK][12];
    while (fgets(line, sizeof line, stdin)) {
        int n = tokenize(line, in), m;
        struct node *root;
        if (n == 0) continue;
        m = toPostfix(in, n, post);
        root = build(post, m);
        printf("PREFIX:"); preorder(root); printf("\n");
        printf("POSTFIX:"); postorder(root); printf("\n");
        freeTree(root);
    }
    return 0;
}
Sample run · Nov 2025 Q6 and model Q13b · real output from gcc

Input (stdin)

(A+B*C)-D-E*F-(G-H/I)
a+b*c/d+(e*f+g)*h

Output (stdout)

PREFIX: - - - + A * B C D * E F - G / H I
POSTFIX: A B C * + D - E F * - G H I / - -
PREFIX: + + a / * b c d * + * e f g h
POSTFIX: a b c * d / + e f * g + h * +

Open in the Code Lab →

Complexity

Building from postfix and evaluating are both O(n) for n symbols.

Common mistakes

  • Choosing the first operator as the root in A − B − C.
  • Swapping left and right children for − and /.
  • Grouping b*c/d as b*(c/d).

Asked in KTU exams (2)

Quick check — can you get them all?

Question 1

Q1.In A − B − C, which operator is the root?

Question 2

Q2.Postorder traversal of an expression tree gives…

Question 3

Q3.To build an expression tree from postfix, you use a stack of…

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Leaves = operands, internal nodes = operators.
  • Root = the operator applied last.
  • In/pre/post-order → infix/prefix/postfix.
  • From postfix: stack of subtrees, pop right first.

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — §5.3 (arithmetic expressions as trees)

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)