Program to build and evaluate an expression tree using Python

Suppose, we are given the postfix traversal of an expression tree. We have to build an expression tree from the given postfix traversal, and then evaluate the expression. We return the root of the expression tree and the evaluated value of the tree.

So, if the input is like:

* + + 1 2 3 4 (1 + 2) * (3 + 4) = 21

The postfix order given as input of the tree is ['1', '2', '+', '3', '4', '+', '*']. The expression if evaluated, becomes (1 + 2) * (3 + 4), which equals 21.

Algorithm

To solve this, we will follow these steps ?

  • Use a stack to build the tree by processing postfix elements from right to left

  • For each element, create a node and attach children from the stack if it's an operator

  • Evaluate the tree recursively by applying operators to left and right subtree values

Implementation

LEFT = 0
RIGHT = 1

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def evaluate(root):
    if root.val.isnumeric():
        return int(root.val)
    
    left_val = evaluate(root.left)
    right_val = evaluate(root.right)
    
    if root.val == '+':
        return left_val + right_val
    elif root.val == '-':
        return left_val - right_val
    elif root.val == '*':
        return left_val * right_val
    elif root.val == '/':
        return left_val // right_val

def buildTree(postfix):
    root = None
    stack = []
    
    while postfix:
        curr = postfix.pop()
        curr_node = Node(curr)
        
        if not root:
            root = curr_node
        
        if stack:
            parent, side = stack.pop()
            if side == LEFT:
                parent.left = curr_node
            else:
                parent.right = curr_node
        
        if not curr.isnumeric():
            stack.append((curr_node, LEFT))
            stack.append((curr_node, RIGHT))
    
    return root

# Test with the example
postfix_expression = ['1', '2', '+', '3', '4', '+', '*']
root = buildTree(postfix_expression)
result = evaluate(root)
print(f"Result: {result}")

The output of the above code is ?

Result: 21

How It Works

The algorithm processes the postfix expression from right to left using a stack:

  1. Building Phase: For each element, create a node. If it's an operator, attach two children from the stack (right child first, then left child)

  2. Evaluation Phase: Recursively evaluate left and right subtrees, then apply the operator at the current node

Example with Different Expression

# Example: (5 - 2) * 3 = 9
postfix_expr = ['5', '2', '-', '3', '*']
tree_root = buildTree(postfix_expr)
output = evaluate(tree_root)
print(f"Expression result: {output}")
Expression result: 9

Conclusion

Expression trees can be efficiently built from postfix notation using a stack-based approach. The evaluation is performed through recursive traversal, making it easy to handle complex nested expressions.

Updated on: 2026-03-25T21:05:17+05:30

2K+ Views

Advertisements