1 Replies - 3243 Views - Last Post: 03 January 2011 - 01:56 PM Rate Topic: -----

#1 LillianIs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 14-May 10

Prefix evaluation using trees

Posted 03 January 2011 - 12:34 PM

A. Write a program to read an arithmetic expression in prefix notation and
place the operators and operands in an expression tree. Then write the
expression in infix notation with full parentheses and print its final value.
Assume that the only operators are binary, the variables are single letters, the
constants are single digits and that there are no blanks. The user should input
the values for the single letter variables.

// prefix binaryTree.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include"bintree.h"
#include <iostream>
#include<string>
using namespace std;

void construct(bintree* ,string); 

int _tmain(int argc, _TCHAR* argv[])
{
	string prefix;
	bintree* tree= new bintree;

	cout<<"please enter the expression You want to evaluate: "<<endl;
	cin>>prefix;
	int size= (prefix.length());
	construct (tree, prefix);

	return 0;
}

void construct(bintree* r, string exp)
{
	int i=1;

	if (exp[0]=='+' || exp[0]=='-'|| exp[0]=='*' || exp[0]=='/')
	{
		r->retrieveroot();
		r->insertroot(exp[0]);
		cout<<"Root: "<<r->retrieverootinfo()<<endl;
	}

	r->retrieveleft();
	r->insertroot(exp[i]);
	cout<<"Left: "<<r->retrieverootinfo()<<endl;
	r->retrieveright();
	r->insertroot(exp[i]);
	cout<<"Right: "<<r->retrieverootinfo()<<endl;

	if (isdigit(exp[i]))
	{
		construct (r->retrieveright(), exp);
	}
	else 
	{
		construct (r->retrieveleft(), exp);
	}

}


This is my code for taking the prefix from the user.. but it gives out the correct root and zeros for the left and right children

Can anyone help pleasee ??!!

Is This A Good Question/Topic? 0
  • +

Replies To: Prefix evaluation using trees

#2 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1635
  • View blog
  • Posts: 3,113
  • Joined: 30-May 10

Re: Prefix evaluation using trees

Posted 03 January 2011 - 01:56 PM

There isn't much to go on, since you didn't post your .h file, or all the other methods.

FWIW, what kind of test cases did you run?

Create some automated tests like so.
std::string tests[] = {
    "3",
    "+34",
    "+34-5"
    // and so on
};

for ( i = 0 ; i < N ; i++ ) {
	string prefix = tests[i];
	bintree* tree= new bintree;
	int size= (prefix.length());
	construct (tree, prefix);
}


You can build up tests as you go.

When you're done with the auto tests, drop into an interactive session like you have at the moment.
When you find a test that doesn't work, add it to your array of tests so that you know it is fixed (and remains fixed) after editing the code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1