Can someone please find the error in code. Gives runtime error "Segmentation Fault" .Expression Tree. I am using a variable for keeping value of expression. It is recursive program. please provide how it can fall into segmentation fault.
This is common problem from tree data structure . Given a full binary expression tree consisting of basic binary operators (+ , – ,*, /) and some integers, Your task is to evaluate the expression tree.
class Solution
{
public:
/*You are required to complete below method */
void cal(node* root, stack<string>& sign, stack<int>& num, int& sum)
{
if (root == NULL)
{
return;
}
if (root->data == "+" || root->data == "-" || root->data == "/" || root->data == "*")
{
sign.push(root->data);
}
else
{
num.push(stoi(root->data));
}
cal(root->left, sign, num, sum);
cal(root->right, sign, num, sum);
int a = num.top();
num.pop();
int b = num.top();
num.pop();
string sign1 = sign.top();
sign.pop();
if (sign1 == "+")
{
sum = a + b;
}
if (sign1 == "*")
{
sum = a * b;
}
if (sign1 == "-")
{
sum = a - b;
}
if (sign1 == "/")
{
sum = a / b;
}
num.push(sum);
return;
}
int evalTree(node* root)
{
// Your code here
cout << "jh" << endl;
stack<string> sign;
stack<int> num;
int res = 0;
cal(root, sign, num, res);
return res;
}
};