Counting Nodes

Step 5: Counting Nodes

Add a third visitor to prove the point again. CountVisitor returns how many nodes the tree contains.

  • visit_num(node) returns 1 (a leaf is one node)
  • visit_add(node) returns 1 + left count + right count
  • visit_mul(node) returns 1 + left count + right count

where the child counts come from node.left.accept(self) and node.right.accept(self). Three operations now share the same nodes, each living entirely in its own visitor.

Hints
Starter code
class Num:
    def __init__(self, value):
        self.value = value

    def accept(self, visitor):
        return visitor.visit_num(self)


class Add:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def accept(self, visitor):
        return visitor.visit_add(self)


class Mul:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def accept(self, visitor):
        return visitor.visit_mul(self)


class EvalVisitor:
    def visit_num(self, node):
        return node.value

    def visit_add(self, node):
        return node.left.accept(self) + node.right.accept(self)

    def visit_mul(self, node):
        return node.left.accept(self) * node.right.accept(self)


class PrintVisitor:
    def visit_num(self, node):
        return str(node.value)

    def visit_add(self, node):
        return "(" + node.left.accept(self) + " + " + node.right.accept(self) + ")"

    def visit_mul(self, node):
        return "(" + node.left.accept(self) + " * " + node.right.accept(self) + ")"


class CountVisitor:
    def visit_num(self, node):
        """Return the node count for a Num node (a leaf counts as 1)."""
        # TODO: return 1
        pass

    def visit_add(self, node):
        """Return 1 plus the node counts of both children."""
        # TODO: return 1 + node.left.accept(self) + node.right.accept(self)
        pass

    def visit_mul(self, node):
        """Return 1 plus the node counts of both children."""
        # TODO: return 1 + node.left.accept(self) + node.right.accept(self)
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.