Skip to content
uconn code

uconn codeExpression tree

Expression tree

CSE 124 · 2000 · C++

The follow-up to the expression compiler: instead of evaluating straight from a stack, build a binary tree of operators and operands, then traverse it to print the expression in each notation.

Source code

4 files, 1,364 lines, exactly as written apart from line endings.

exprtree.cpp · 77 lines
// Stephen Bassoli
// CSE 124 Section 01
// Lab 7

#include <fstream.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include "BinTree.h"
#include "stack.h"

int main()
{
	Operator<char> Stack;
	BinTree<char> Tree;
	char* input;
	char* string;
	char useless;
	bool repeat = true;
	int length;
	int index = 0;

	while (repeat)
	{
		ofstream outfile("equation.txt");
		assert(outfile);
		cout << "Enter equation, each number or variable must be one character.\n";
		cout << "Seperate characters by spaces:\n";
		input = new char[100];
		cin.getline(input,100);
		outfile  << input;
		delete [] input;
		string = new char[100];
		strcpy(string,Stack.Convert(outfile));
		length = strlen(string);
		index = length - 1;
		for (index ; index >= 0 ; index--)
		{
			Tree.Insert(string[index]);
		}
		delete [] string;
		cout << "Tree Layout:\n";
		Tree.PrintTree();
		cout << "Prefix expression before simplification...\n";
		Tree.PreOrder();
		cout << "Infix expression before simplification...\n";
		Tree.InOrder();
		cout << "Postfix expression before simplification...\n";
		Tree.PostOrder();
		cout << "Enter any character to simplify: ";
		cin >> useless;
		Tree.FindDouble();
		Tree.PostOrderFind();
		cout << "\nSimplified Tree Layout:\n";
		Tree.PrintTree();
		cout << "Prefix expression after simplification...\n";
		Tree.PreOrder();
		cout << "Infix expression after simplification...\n";
		Tree.InOrder();
		cout << "Postfix expression after simplification...\n";
		Tree.PostOrder();
		cout << "Enter another expression? (y/n) ";
		cin >> useless;
		useless = tolower(useless);
		if (useless == 'y')
		{
			repeat = true;
			Tree.ClearTree();
			cin.ignore(256,'\n');
		}
		else
			repeat = false;
		
	}
	return 0;
}

exprtree.cpp as plain text

bintree.h · 702 lines

bintree.h as plain text

treenode.h · 249 lines

treenode.h as plain text

stack.h · 336 lines

stack.h as plain text