Lesson 13 +30 XP

Tree Manipulation Algorithms & Building Expression Trees

Tree Manipulation Algorithms & Building Expression Trees

The syllabus lists tree manipulation algorithms separately from traversals. Almost every one of them is a small recursive function that follows the same pattern: handle the empty tree, recurse on the left and right subtrees, combine the answers.

C
typedef struct node {
    int data;
    struct node *left, *right;
} Node;

1. Counting Algorithms

C
int countNodes(Node *t) {               /* total nodes */
    if (t == NULL) return 0;
    return 1 + countNodes(t->left) + countNodes(t->right);
}

int countLeaves(Node *t) {              /* nodes with no children */
    if (t == NULL) return 0;
    if (t->left == NULL && t->right == NULL) return 1;
    return countLeaves(t->left) + countLeaves(t->right);
}

int countInternal(Node *t) {            /* nodes with at least one child */
    if (t == NULL || (t->left == NULL && t->right == NULL)) return 0;
    return 1 + countInternal(t->left) + countInternal(t->right);
}

int sumNodes(Node *t) {
    if (t == NULL) return 0;
    return t->data + sumNodes(t->left) + sumNodes(t->right);
}

2. Height (Depth) of a Tree

C
int height(Node *t) {                   /* height in edges; empty tree = -1 */
    if (t == NULL) return -1;
    int hl = height(t->left), hr = height(t->right);
    return 1 + (hl > hr ? hl : hr);
}

Some textbooks count height in levels (empty tree = 0, single node = 1). Say which convention you use in the exam.

3. Copying, Mirroring and Comparing

C
Node *copyTree(Node *t) {               /* preorder: copy root, then children */
    if (t == NULL) return NULL;
    Node *n = malloc(sizeof(Node));
    n->data  = t->data;
    n->left  = copyTree(t->left);
    n->right = copyTree(t->right);
    return n;
}

void mirror(Node *t) {                  /* swap left and right everywhere */
    if (t == NULL) return;
    Node *tmp = t->left; t->left = t->right; t->right = tmp;
    mirror(t->left);
    mirror(t->right);
}

int identical(Node *a, Node *b) {       /* same shape and same data */
    if (a == NULL && b == NULL) return 1;
    if (a == NULL || b == NULL) return 0;
    return a->data == b->data && identical(a->left, b->left)
                              && identical(a->right, b->right);
}

4. Searching and Deleting a Whole Tree

C
Node *find(Node *t, int key) {          /* general binary tree: search both sides */
    if (t == NULL || t->data == key) return t;
    Node *r = find(t->left, key);
    return r ? r : find(t->right, key);
}

void deleteTree(Node *t) {              /* POSTORDER: children before parent */
    if (t == NULL) return;
    deleteTree(t->left);
    deleteTree(t->right);
    free(t);
}

Deleting must be postorder: if the parent were freed first, the pointers to its children would be lost.

5. Worked Example

TEXT
            A
         /     \
        B       C
       / \     / \
      D   E   G   H
         /       / \
        F       J   K
               /
              L
FunctionResultReason
countNodes11A B C D E F G H J K L
countLeaves5D, F, G, L, K
countInternal6A, B, C, E, H, J (11 − 5)
height (edges)4A → C → H → J → L
mirror, then inorderK H J L C G A E F B Dthe original inorder reversed

In any binary tree, the number of leaves = (number of nodes with two children) + 1. Here: nodes with two children are A, B, C, H → 4, and leaves = 5 ✓.

6. Building an Expression Tree from Postfix

Scan the postfix expression left to right with a stack of tree pointers:

  1. Operand → create a one-node tree and push it.
  2. Operator → pop two trees (first pop = right child, second pop = left child), make a new node with the operator and push it.
  3. At the end, the single tree left on the stack is the expression tree.
C
Node *buildFromPostfix(const char *postfix) {
    Node *stack[50]; int top = -1;
    for (int i = 0; postfix[i]; i++) {
        char c = postfix[i];
        if (c == ' ') continue;
        Node *n = newNode(c);
        if (isalnum(c)) stack[++top] = n;       /* operand */
        else {                                  /* operator */
            n->right = stack[top--];
            n->left  = stack[top--];
            stack[++top] = n;
        }
    }
    return stack[top];
}

Trace for a b + c d e + * *:

SymbolActionStack (bottom → top)
a, bpush leavesa, b
+pop b, a → (a + b)(a+b)
c, d, epush leaves(a+b), c, d, e
+pop e, d → (d + e)(a+b), c, (d+e)
×pop (d+e), c → (c × (d+e))(a+b), (c×(d+e))
×pop both → root ×((a+b) × (c×(d+e)))
TEXT
          *
        /   \
       +     *
      / \   / \
     a   b c   +
              / \
             d   e

From a prefix expression the same idea works scanning right to left (first pop = left child).

7. Evaluating an Expression Tree

C
int eval(Node *t) {                    /* postorder evaluation */
    if (t->left == NULL && t->right == NULL) return t->data - '0';
    int x = eval(t->left), y = eval(t->right);
    switch (t->data) {
        case '+': return x + y;
        case '-': return x - y;
        case '*': return x * y;
        case '/': return x / y;
    }
    return 0;
}

For a = 1, b = 2, c = 3, d = 4, e = 5 the tree above gives (1 + 2) × (3 × (4 + 5)) = 3 × 27 = 81.

Uses of expression trees: compilers build them while parsing; they convert easily between infix, prefix and postfix; they can be simplified (constant folding) and evaluated recursively.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Write recursive C functions to count (i) all nodes, (ii) leaf nodes, and (iii) the height of a binary tree. (7.5 Marks)
  • Write: the node structure, the three functions with base cases, and a small example tree with the answers.
  • Q2. Construct the expression tree for the postfix expression a b + c d e + * * and give its prefix and infix forms. (5 Marks)
  • Write: the stack trace table, the final tree, prefix * + a b * c + d e, infix ((a + b) * (c * (d + e))).
  • Q3. Write algorithms to copy a binary tree and to test whether two binary trees are identical. (5 Marks)