6.6Tree Applications
Expression trees
When a compiler reads an expression like (3 + 4) * (5 - 2), it first turns it into a tree. In an expression tree the inner nodes are operators and the leaves are operands; no parentheses are needed, because the shape of the tree says which operation comes first. In this lesson you build an expression tree from a postfix expression with a stack and evaluate it recursively.
- The structure of an expression tree and why it needs no parentheses
- How to build the tree from a postfix expression with a stack
- How to evaluate the tree recursively, and which notation each traversal gives
1Idea
In the tree for (3 + 4) * (5 - 2) the root is *, because that is the last operation to run. Its left subtree is 3 + 4 and its right subtree is 5 - 2. The operands of an operation are its children; an operation that runs earlier sits lower in the tree.
The easiest way to build the tree is to use the postfix form of the expression: 3 4 + 5 2 - *. You saw how to convert to postfix in Converting infix to postfix. The building rule is very close to evaluating postfix; only the stack holds subtrees instead of numbers:
- Read the characters from left to right and make a node for each one.
- If the character is a digit, push the node on the stack. It is a leaf.
- If the character is an operator, pop two nodes from the stack. The first one popped becomes the right child, the second one the left child. Push the new node; it is now the root of a subtree.
- When the expression ends, a single node is left on the stack: the root of the tree.
Evaluation is recursive: if a node is a leaf, its value is the digit itself. Otherwise the left subtree is evaluated first, then the right one, and the operator at the root is applied to both. This is a postorder traversal: children first, the root last.
| Traversal | Order on this tree | Notation |
|---|---|---|
| Preorder | * + 3 4 - 5 2 | Prefix |
| Inorder | 3 + 4 * 5 - 2 | Infix (no parentheses) |
| Postorder | 3 4 + 5 2 - * | Postfix |
An inorder traversal gives the infix expression, but the parentheses are lost: 3 + 4 * 5 - 2 is a different expression. For correct infix, write the subtree of every inner node in parentheses: first (, then the left subtree, the root, the right subtree, then ).
The code works with single-digit numbers and the operators + - * /. In C and Java / is integer division; Python uses // for the same result. For numbers with more digits you first split the expression into tokens; the idea stays the same.
2Step by step
The postfix expression is 34+52-*, that is (3 + 4) * (5 - 2). Nodes are shown in their final places in the tree as soon as they are made; the box on the right is the stack, with each subtree written in infix.
3is a digit. A leaf node is made and pushed on the stack.4is a digit too. It is pushed as a leaf. The stack holds two subtrees: 3 and 4.+is an operator. A new node is made; now it takes its two operands from the stack.- 4 is popped first and becomes the right child, then 3 is popped and becomes the left child. The
+node is pushed; the stack now holds one subtree: (3+4). 5is a digit. It is pushed.2is a digit. It is pushed. The stack holds three subtrees.-is an operator. 2 goes to the right, 5 to the left, and the-node is pushed. Stack: (3+4), (5-2).*is an operator. (5-2) is popped first and becomes the right child, then (3+4) becomes the left child. The expression has ended; the*node left on the stack is the root.- evaluate(root). The left subtree gives 3 + 4 = 7 and the right one 5 - 2 = 3. The
*at the root is applied to both: 7 * 3 = 21.
struct ExprNode { char ch; struct ExprNode* left; struct ExprNode* right;}; struct ExprNode* newNode(char ch) { struct ExprNode* n = malloc(sizeof(struct ExprNode)); n->ch = ch; n->left = NULL; n->right = NULL; return n;} bool isOperator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/';} struct ExprNode* build(const char* postfix) { struct ExprNode* stack[100]; int top = -1; for (int i = 0; postfix[i] != '\0'; i++) { struct ExprNode* n = newNode(postfix[i]); if (isOperator(postfix[i])) { n->right = stack[top--]; // the right operand comes off first n->left = stack[top--]; } stack[++top] = n; // a leaf or a new subtree } return stack[top]; // the one left is the root} int evaluate(struct ExprNode* root) { if (!isOperator(root->ch)) return root->ch - '0'; // leaf: a digit int a = evaluate(root->left); int b = evaluate(root->right); switch (root->ch) { case '+': return a + b; case '-': return a - b; case '*': return a * b; default: return a / b; }}class ExprNode { char ch; ExprNode left, right; ExprNode(char ch) { this.ch = ch; }} boolean isOperator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/';} ExprNode build(String postfix) { java.util.ArrayDeque<ExprNode> stack = new java.util.ArrayDeque<>(); for (char ch : postfix.toCharArray()) { ExprNode n = new ExprNode(ch); if (isOperator(ch)) { n.right = stack.pop(); // the right operand comes off first n.left = stack.pop(); } stack.push(n); // a leaf or a new subtree } return stack.pop(); // the one left is the root} int evaluate(ExprNode root) { if (!isOperator(root.ch)) return root.ch - '0'; // leaf: a digit int a = evaluate(root.left); int b = evaluate(root.right); switch (root.ch) { case '+': return a + b; case '-': return a - b; case '*': return a * b; default: return a / b; }}class ExprNode: def __init__(self, ch): self.ch = ch self.left = None self.right = None def is_operator(ch): return ch in "+-*/" def build(postfix): stack = [] for ch in postfix: n = ExprNode(ch) if is_operator(ch): n.right = stack.pop() # the right operand comes off first n.left = stack.pop() stack.append(n) # a leaf or a new subtree return stack[-1] # the one left is the root def evaluate(root): if not is_operator(root.ch): return int(root.ch) # leaf: a digit a = evaluate(root.left) b = evaluate(root.right) if root.ch == "+": return a + b if root.ch == "-": return a - b if root.ch == "*": return a * b return a // bThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Building reads each character once and does a fixed number of stack operations for each. Evaluation visits each node once. Both take O(n) for an expression of length n.
The tree has n nodes. While building, the stack grows to at most n elements; while evaluating, the recursion goes as deep as the height of the tree.
You could evaluate the same expression directly with a stack, without building a tree. The tree pays off where the expression is evaluated, transformed or printed many times, as in compilers.
4Common mistake
The most common mistake is mixing up the places of the two nodes popped from the stack:
n->left = stack[top--]; // wrong: the first one popped is the right operand, not the leftn->right = stack[top--];For + and * the result does not change, so the bug slips by. But with this code 5 2 - becomes 2 - 5 = -3. The top of the stack holds the operand pushed last, which is the one on the right.
5Try it
For the tree built from the postfix expression a b c * +, what are the root and its right child?
The answer is B. a, b and c are pushed. * takes c first (right), then b (left). + takes the * subtree first (right), then a (left). The root is +, and the expression is a + b * c.
Show the answer
The answer is B. a, b and c are pushed. * takes c first (right), then b (left). + takes the * subtree first (right), then a (left). The root is +, and the expression is a + b * c.
Which notation does the preorder traversal of an expression tree give?
The answer is B. Preorder writes the root first, so an operator comes before its operands. That is prefix notation: * + 3 4 - 5 2.
Show the answer
The answer is B. Preorder writes the root first, so an operator comes before its operands. That is prefix notation: * + 3 4 - 5 2.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.