You are here:

C++/Help with expression tree


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:

---------- 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:

double getValue(ExpNode *node){
  if(node->kind == NUMBER){
    return node->number;
    double leftVal = getValue(node->left);
    double rightVal = getValue(node->right);
       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: - 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:

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


All Answers

Answers by Expert:

Ask Experts


Amit Kumar


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.

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

©2017 All rights reserved.