這是一個表達式樹,我必須爲一個類做出,但評估函數調用時不顯示任何東西。任何想法,我錯了什麼地方或我可能會失蹤?從我們在課堂上學到的東西看,它應該運行。表達式樹評估錯誤
#include <iostream>
#include <string>
using namespace std;
class TreeNode //Leaf Node
{
public:
TreeNode(char key, int data, TreeNode* p) //constructor
{
this->key = key;
this->data = data;
n = 1;
left = NULL;
right = NULL;
parent = p;
}
TreeNode * left;
TreeNode * right;
TreeNode * parent;
char key;
int data;
int n;
};
class ExpressionTree //expression tree
{
public:
void create(); //creates binary expression tree
TreeNode * root; //instance of TreeNode
int Evaluate(TreeNode * n); //evaluates tree
void InOrder(TreeNode * n); //traverses tree InOrder
void PreOrder(TreeNode *n); //traverses tree PreOrder
void PostOrder(TreeNode *n); //traverses tree PostOrder
};
void ExpressionTree::create() //creates binary expression tree
{
root = new TreeNode('*',3,0);
root->left = new TreeNode('+',5,root);
root ->left->left = new TreeNode('2',2,root->left);
root ->left->right = new TreeNode('3',3,root->left);
root->right = new TreeNode('5',5,root);
}
int ExpressionTree::Evaluate(TreeNode *n) //Evaluates tree
{
int answer = 0;
switch(n->key) //switch statement to decide what operator is being used
{
case '+':
answer = (Evaluate(n->left)+ Evaluate(n->right));
break;
case '-':
answer = (Evaluate(n->left)- Evaluate(n->right));
break;
case '*':
answer = (Evaluate(n->left)* Evaluate(n->right));
break;
case '/':
answer = (Evaluate(n->left)/ Evaluate(n->right));
break;
}
return answer; //returns answer
}
void ExpressionTree::InOrder(TreeNode * n) //traverses the tree InOrder
{
if (n) {
InOrder(n->left);
cout << n->key << " ";
InOrder(n->right);
}
}
void ExpressionTree::PreOrder(TreeNode * n) //traverses the tree PreOrder
{
if (n) {
cout << n->key << " ";
PreOrder(n->left);
PreOrder(n->right);
}
}
void ExpressionTree::PostOrder(TreeNode * n)//traverses the tree PostOrder
{
if (n) {
PostOrder(n->left);
PostOrder(n->right);
cout << n->key << " ";
}
}
int main() //main program
{
ExpressionTree * mytree; //creates instance of ExpressionTree
mytree->create();
cout<<"The Answer is: "<<endl;
mytree->Evaluate(mytree->root);
cout<<endl;
cout<<"In InOrder"<<endl;
mytree->InOrder(mytree->root);
cout<<endl;
cout<<"In PreOrder"<<endl;
mytree->PreOrder(mytree->root);
cout<<endl;
cout<<"In PostOrder"<<endl;
mytree->PostOrder(mytree->root);
cout<<endl;
}
_Seems是failing_是很難描述的描述。請正確描述問題 – yizzlez
'程序接收到的信號SIGSEGV,ExpressionTree :: create(this = 0x1)中的Segmentation fault在x.cpp:42 root = new TreeNode('*',3,0);' –
請原諒我,我意味着什麼都不顯示。 – Josamoda