Expression Tree

 

What is an Expression Tree?

  • An expression tree is a binary tree used to represent arithmetic expressions.

  • In an expression tree:

    • Each internal node (non-leaf) contains an operator (+, -, *, /).

    • Each leaf node contains an operand (like a number or variable).

Example:

Expression:


(3 + 5) * (2 - 4)

Expression Tree:


* / \ + - / \ / \ 3 5 2 4

How to create an Expression Tree from an Expression?

There are two common ways:

  • From postfix (easiest and standard)

  • From infix (needs more work like using a stack and precedence rules)

We usually use postfix expression to easily build the tree.

Steps to Create from Postfix:

  1. Read the postfix expression left to right.

  2. If operand → create a node and push onto stack.

  3. If operator

    • Pop two nodes from stack.

    • Create a new node with the operator.

    • Set the two popped nodes as children (left and right).

    • Push the new node back onto the stack.

  4. After all symbols are processed, top of stack is the root of the expression tree.


Algorithm (from postfix)

Create an empty stack
For each symbol in postfix expression:
    if symbol is operand:
        create node, push it onto stack
    else if symbol is operator:
        pop two nodes
        create new node with operator
        set popped nodes as left and right children
        push new node onto stack
Root = top of stack

Simple C Program to Create and Traverse an Expression Tree
Note; The input must be an expression with single digits  Eg:23+45-*

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h> // for isdigit()

// Tree node structure
struct Node {
    char data;
    struct Node *left, *right;
};

// Stack node structure
struct Stack {
    struct Node* data;
    struct Stack* next;
};

struct Stack* top = NULL;

// Function to create new tree node
struct Node* createNode(char value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->left = newNode->right = NULL;
    return newNode;
}

// Stack operations
void push(struct Node* treeNode) {
    struct Stack* temp = (struct Stack*)malloc(sizeof(struct Stack));
    temp->data = treeNode;
    temp->next = top;
    top = temp;
}

struct Node* pop() {
    if (top == NULL) return NULL;
    struct Stack* temp = top;
    struct Node* res = top->data;
    top = top->next;
    free(temp);
    return res;
}

// Create Expression Tree from postfix expression
struct Node* createExpressionTree(char postfix[]) {
    int i = 0;
    char symbol;
    while ((symbol = postfix[i]) != '\0') {
        if (isdigit(symbol)) { // Operand
            struct Node* operandNode = createNode(symbol);
            push(operandNode);
        } else { // Operator
            struct Node* operatorNode = createNode(symbol);
            operatorNode->right = pop();
            operatorNode->left = pop();
            push(operatorNode);
        }
        i++;
    }
    return pop(); // Root node
}

// Inorder traversal (infix)
void inorder(struct Node* root) {
    if (root != NULL) {
        if(root->left && root->right) printf("(");
        inorder(root->left);
        printf("%c", root->data);
        inorder(root->right);
        if(root->left && root->right) printf(")");
    }
}

// Preorder traversal (prefix)
void preorder(struct Node* root) {
    if (root != NULL) {
        printf("%c", root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

// Postorder traversal (postfix)
void postorder(struct Node* root) {
    if (root != NULL) {
        postorder(root->left);
        postorder(root->right);
        printf("%c", root->data);
    }
}

int main() {
    struct Node* root = NULL;
    int choice;
    char postfix[100];

    do {
        printf("\nMenu\n----\n");
        printf("1. Create Expression Tree\n");
        printf("2. Inorder Traversal (Infix Expression)\n");
        printf("3. Preorder Traversal (Prefix Expression)\n");
        printf("4. Postorder Traversal (Postfix Expression)\n");
        printf("5. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        getchar(); // clear input buffer

        switch(choice) {
            case 1:
                printf("Enter postfix expression: ");
                scanf("%s", postfix);
                root = createExpressionTree(postfix);
                printf("Expression Tree Created Successfully.\n");
                break;
            case 2:
                if(root == NULL) printf("Create the tree first!\n");
                else {
                    printf("Inorder Traversal (Infix): ");
                    inorder(root);
                    printf("\n");
                }
                break;
            case 3:
                if(root == NULL) printf("Create the tree first!\n");
                else {
                    printf("Preorder Traversal (Prefix): ");
                    preorder(root);
                    printf("\n");
                }
                break;
            case 4:
                if(root == NULL) printf("Create the tree first!\n");
                else {
                    printf("Postorder Traversal (Postfix): ");
                    postorder(root);
                    printf("\n");
                }
                break;
            case 5:
                printf("Exiting program.\n");
                exit(0);
            default:
                printf("Invalid choice! Try again.\n");
        }

    } while(1);

    return 0;
}

Comments

Popular posts from this blog

Data Structures Lab PCCSL307 KTU 2024 Scheme - Dr Binu V P

Sparse Matrix - Transpose and Addition

Polynomial Addition using Arrays