You are here:

- Home
- Computing/Technology
- C/C++
- C++
- Help with expression tree

Advertisement

QUESTION: Hello, I need help setting up this expression tree. What I want to do is to let the user

enter a prefix notation. I thought about storing it in a character array. I want

to send it to the functions so it can perform the calculations so it will be

able to evaluate the tree in order to get a single answer. I think I know how to

set up everything except the main(). I was wondering if you could help me out?

Thank you so much for your time

ANSWER: Dear Jared

Why dont you use std::string in place of C-style character array. This will make your life simpler:

#include <iostream>

int evaluateByFormingTree(const std::string& s)

{

return 0; //TODO

}

int main() {

std::string s;

std::getline(std::cin, s);

int result = evaluateByFormingTree(s);

std::cout << "Result after evaluation is " << result << "\n";

return 0;

}

Also see: http://www-cse.ucsd.edu/users/calder/UCSDProgramContest/sheets/cpp-hints

---------- FOLLOW-UP ----------

QUESTION: Ok, I found this function to determine the value of the expression tree, along with a struct that goes with this. It was found on this website:

http://math.hws.edu/eck/cs225/s03/binary_trees/

double getValue(ExpNode *node){

if(node->kind == NUMBER){

return node->number;

}

else

{

double leftVal = getValue(node->left);

double rightVal = getValue(node->right);

switch(node->op){

case '+': return leftVal + rightVal;

case '-': return leftVal - rightVal;

case '*': return leftVal * rightVal;

case '/': return leftVal / rightVal;

}

}

}

Now I am trying to figure out how to insert the numbers and operands in the tree. Do you have any suggestions? Thank you for your time and the help.

Dear Jared

The code you have right now feels more like C than C++.

It seems you're looking to assemble the answer from the net. It would be great if you spend some time in understanding the code and learning the language. One good resource is: http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html - this book has both an online and print version.

However, you seem to be in a hurry this time. Then go through the link you sent. If you understand that article you should be able to pick code from that site to complete your solution. In addition, you will need to code the parser for the input mathematical expression. For an example, see Stroustrup's book on C++ Programming Language.

Also see: http://www.awprofessional.com/articles/article.asp?p=26135&rl=1

Please spend some time on the problem. Otherwise the answer will be too long for this forum.

I can answer Cplusplus language and library questions, including STL, ACE, Boost. I have a good background in Mathematics.

Programming in CPP for about 8 years. Industry experience of 4 years. **Education/Credentials**

Bachelors and Masters in Computer Science from Indian Institute of Technology Delhi.