Я реализую двоичное дерево для хранения арифметического выражения в 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;
}
Да, я хочу передать параметр по ссылке. Но я действительно не знаю, как это сделать. Я думал, что передача указателя передается ссылкой, однако на этот раз он не работает. – Linh
'Node * insertNode (int e, Node * & node) {...' –
Получите хорошую книгу на C++. Он объяснит, что такое ссылки, и различия между передачей по значению и передачей по ссылке. –