【发布时间】:2016-07-19 06:44:53
【问题描述】:
我正在实现一个二叉树来存储 C++ 中的算术表达式。但是,我在向树中插入节点时遇到了一些麻烦。我想通过解析元素和地址将节点插入树。
它崩溃了,可能是因为节点没有附加到树上。
希望你们能帮我解决这个问题。欢迎提出其他实现二叉树来存储算术表达式的方法的想法。
这是我的程序:
struct Node{
int element;
Node* left;
Node* right;
Node(int e){
this->element = e;
this->left = NULL;
this->right = NULL;
}
bool isInternal(){
return (this->left != NULL || this->right != NULL);
}
void print(){
if(isInternal()){
switch(this->element){
case 1:
cout << " + ";
break;
case 2:
cout << " - ";
break;
case 3:
cout << " * ";
break;
case 4:
cout << " / ";
break;
}
}
else
cout << this->element;
}
bool hasLeft(){
return (this->left != NULL);
}
bool hasRight(){
return (this->right != NULL);
}
};
class BinaryTree{
public:
Node* root;
void clearTree(Node* t){
if(t == NULL)
return;
if(t->left != NULL)
clearTree(t->left);
if(t->right != NULL)
clearTree(t->right);
delete t;
return;
}
BinaryTree(){
root = NULL;
}
~BinaryTree(){
clearTree(root);
}
bool isEmpty(){
return (root == NULL);
}
Node* insertNode(int e, Node* node){
Node* newNode = new Node(e);
node = newNode;
return node;
}
void printExpression(Node* node){
if(node->hasLeft()){
cout << "(";
printExpression(node->left);
}
node->print();
if(node->hasRight()){
printExpression(node->right);
cout << ")";
}
}
};
int main(){
BinaryTree* bt = new BinaryTree();
Node* root = bt->root;
bt->insertNode(1, root);
Node* n1 = bt->insertNode(3, root->left);
bt->insertNode(2, n1->left);
Node* n2 = bt->insertNode(2, n1->right);
bt->insertNode(4, n2->left);
bt->insertNode(1, n2->right);
Node* n3 = bt->insertNode(3, root->right);
bt->insertNode(3, n3->left);
bt->insertNode(5, n3->right);
bt->printExpression(root);
return 0;
}
【问题讨论】:
标签: c++ binary-tree