노드에 int를 트리에 삽입하려고하는 함수를 만들고 있습니다. 필자가 아는 한, 필자의 삽입 기능은 완벽하게 작동하지만 기능 외에서는 결코 일어나지 않았을 것입니다. 여기에 내 코드입니다 :함수 호출 외부에서 노드 매개 변수를 변경할 수 없습니다.
lcrs.h :
using namespace std;
#include <cstdlib>
#include <iostream>
class node{
public:
int data;
node *right;
node *below;
node()
{
right = NULL;
below = NULL;
}
};
class lcrs{
public:
node *root;
bool search(int, node*);
void print(node*);
void insert(int, node*);
int getHeight(node*);
lcrs()
{
root = NULL;
}
};
그리고 lcrs.cpp :
using namespace std;
#include "lcrs.h"
bool lcrs::search(int x, node *b)
{
if(b == NULL)
return false;
else
{
if(b->data == x)
return true;
else
{
return search(x, b->right) || search(x, b->below);
}
}
}
void lcrs::print(node *z)
{
if(z->right == NULL && z->below == NULL)
{
cout << z->data << endl;
}
else if(z->below == NULL && z->right != NULL)
{
cout << z->data << ", ";
print(z->right);
}
}
else if(z->below != NULL && z->right == NULL)
{
cout << z->data << ", ";
print(z->below);
}
else
{
print(z->right);
print(z->below);
}
}
void lcrs::insert(int x, node *a)
{
if(a == NULL)
{
node *newnode;
newnode = new node;
newnode->data = x;
a = newnode;
cout << a->data << endl;
}
else if(a->data < x)
{
if(a->right != NULL)
{
insert(x, a->right);
}
else
a->right->data = x;
}
else
{
if(a->below != NULL)
{
insert(x, a->below);
}
else
{
a->below->data = x;
}
}
}
int lcrs::getHeight(node *h)
{
int height = 0;
if(h->below != NULL)
{
height ++;
return getHeight(h->below);
}
else
return height;
}
그리고 마지막으로 내 MAIN.CPP :
using namespace std;
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "lcrs.h"
int main()
{
char *temp1;
char *temp2;
temp1 = new char;
temp2 = new char;
lcrs tree;
do{
cout << "LCRS> ";
cin >> temp1;
if(strcmp(temp1, "quit") == 0)
{
return 0;
}
if(strcmp(temp1, "insert") == 0)
{ cin >> temp2;
bool error;
for(int i=0; i<strlen(temp2)-1; i++)
{
if(!isdigit(temp2[i]))
{
cout << "Error!" << endl;
error = true;
}
}
if(!error)
{
tree.insert(atoi(temp2), tree.root);
if(tree.root == NULL)
cout << "Root is null." << endl;
else
cout << tree.root->data << endl;
}
}
else if(strcmp(temp1, "height") == 0)
{
if(tree.root == NULL)
cout << "-1" << endl;
else
cout << tree.getHeight(tree.root);
}
else if(strcmp(temp1, "preorder") == 0)
{
tree.print(tree.root);
}
}while(strcmp(temp1, "quit") !=0);
return 0;
}
그래서 내가 이해 내 기능이 실제로 변경되지 않습니다. 루트이 트리인데 이유를 이해하지 못합니다.
귀하의 도움에 감사드립니다.
조회 패스는 참조로 전달하고 값으로 전달하십시오. 값으로 전달하고 있지만 참조로 전달되는 것처럼 보이기를 원합니다. – John3136