CSC 221

Data Structures

Spring 2008

Burg

 

Program #4

 

Your assignment is to construct and evaluate an expression tree as described on pages 121 to 124 in your book.

 

Implement an expression tree class and a tree node class.  You can call them ExpTree and Tnode.  The expression tree is a binary tree used to evaluated arithmetic expressions.  The code for BinarySearchTree in your book will be useful to you as an example, although it isn't identical to what you need to do for the expression tree.

 

You can use the stack and stack node classes from your previous program, modifying them so that a stack node contains the appropriate type of data.

 

Prompt the user for the name of the input file.

 

The input file should contain multiple lines of postfix expressions. 

 

The postfix expressions should have single-digit positive integers in them – no variables.  They should also contain the operators +, -, *, and /.

 

Your main function should have a while loop that reads lines from the input file as long as lines remain.  Each line should be turned into an expression tree, the expression tree printed, the expression tree evaluated, and the result printed.  Thus, you need the following:

convert function for converting postfix expressions to expression trees

a printTree function for printing the tree, using inorder traversal

an evaluate function for doing the arithmetic to get an answer. 

 

The convert function should be a global function, not belonging to any particular class.  The printTree and evaluate functions should be member functions of the expression tree class.