我正在尝试编写一个对树执行不同功能的程序,到目前为止,除了打印功能外,它们都可以工作。它以前可以工作,但是在尝试解决其他功能中的一些问题时(不弄乱它),现在它们已修复,这个突然不起作用,我不明白为什么。这是我的代码:
主.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); i++)
{
if(!isdigit(temp2[i]))
{
cout << "Error!" << endl;
error = true;
}
}
if(!error)
{
tree.insert(atoi(temp2), tree.root);
}
}
else if(strcmp(temp1, "height") == 0)
{
if(tree.root == NULL)
cout << "-1" << endl;
else
cout << tree.getHeight(tree.root) << endl;
}
else if(strcmp(temp1, "preorder") == 0)
{
cout << "Root is " << tree.root->data << endl;
tree.print(tree.root);
cout << "" << endl;
}
else if(strcmp(temp1, "search") == 0)
{
cin >> temp2;
bool error;
for(int i=0; i<strlen(temp2); i++)
{
if(!isdigit(temp2[i]))
{
cout << "Error!" << endl;
error = true;
}
}
if(!error)
{
if(tree.search(atoi(temp2), tree.root))
cout << "true" << endl;
else
cout << "false" << endl;
}
}
else
{
cout << "Error! " << endl;
}
}while(strcmp(temp1, "quit") !=0);
return 0;
}
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->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 if(z->below != NULL && z->right != NULL)
{
cout << z->data << ",";
print(z->below);
print(z->right);
}
else if(z->right == NULL && z->below == NULL)
{
cout << z->data << "";
}
}
void lcrs::insert(int x, node *&a)
{
if(a == NULL)
{
node *newnode;
newnode = new node;
newnode->data = x;
a = newnode;
}
else if(a->data < x)
{
if(a->right != NULL)
{
insert(x, a->right);
}
else if(a->below != NULL)
{
if(a->below->right != NULL)
{
insert(x, a->below->right);
}
else
{
insert(x, a->below);
}
}
else
{
node *n;
n = new node;
n->data = x;
a->below = n;
}
}
else if(a->data > x)
{
if(a->below != NULL)
{
insert(x, a->below);
}
else
{
node *n;
n = new node;
n->data = x;
a->right = n;
}
}
}
int lcrs::getHeight(node *h)
{
int height = 0;
node *n;
n = new node;
n = h;
while(n->below != NULL || n->right != NULL)
{
if(n->below != NULL)
{
n = n->below;
height ++;
}
else if(n->right != NULL)
{
n = n->right;
}
}
return height;
}
我在tree.print(tree.root)函数调用时遇到了段错误。我在函数的最开始放了一个打印语句,但它从来没有做到这一点,所以我对问题出在哪里有点困惑。
非常感谢您的帮助。