|
楼主 |
发表于 2003-11-24 23:11:41
|
显示全部楼层
the first file: tree.h
struct tree
{
int id;
int data;
tree *left;
tree *right;
};
typedef struct tree treenode;
typedef treenode *b_tree;
class treecreate
{
public:
treecreate();
~treecreate();
b_tree create(int *,int *,int len);
b_tree insert_node(b_tree,int,int);
void preorder(b_tree);
void inorder();
void postorder();
void searchid(int num);
void searchdata(int datanum);
void print();
};
the second file: tree.cpp
#include <iostream>
#include "tree.h"
using namespace std;
treecreate::treecreate()
{
}
treecreate::~treecreate()
{
}
b_tree treecreate::create(int *id,int *data,int len)
{
int i;
b_tree root = NULL;
for (i=0;i<len;i++)
root = insert_node(root,id,data);
return root;
}
b_tree treecreate::insert_node(b_tree root,int nid,int ndata)
{
b_tree newnode;
b_tree currentnode;
b_tree parentnode;
newnode = new tree;
newnode -> id = nid;
newnode -> data = ndata;
newnode -> left = NULL;
newnode -> right = NULL;
if (root == NULL)
return newnode;
else{
currentnode = root;
while (currentnode != NULL)
{
parentnode = currentnode;
if(currentnode->id > nid)
currentnode=currentnode->left;
else
currentnode=currentnode->right;
}
if (parentnode->id > nid)
parentnode->left = newnode;
else
parentnode->right=newnode;
}
return root;
}
/*void treecreate::print()
{
point = root->left;
cout << "Print left_subtree node of root:" << endl;
while (point != NULL)
{
printf("[%2d]-",point->id);
printf("[%2d]\n", point->data);
point=point->left;
}
point = root->right;
cout << "Print right_subtree node of root:" << endl;
while (point != NULL)
{
printf("[%2d]-",point->id);
printf("[%2d]\n",point->data);
point=point->right;
}
}
*/
void treecreate::preorder(b_tree point)
{
if (point != NULL)
{
printf("[%2d]-",point->id);
printf("[%2d]\n",point->data);
preorder(point->left);
preorder(point->right);
}
}
the third file: main.cpp
#include <iostream>
#include "tree.h"
using namespace std;
int main()
{
treecreate p;
b_tree kroot;
int i,index;
int Kid,Kdata;
int idlist[20];
int datalist[20];
index = 0;
cout << endl << "Enter ID:";
cin >> Kid;
cout << endl << "Enter DATA:";
cin >> Kdata;
while (1)
{
idlist[index] = Kid;
datalist[index] = Kdata;
index = index + 1;
cout << endl << "Enter ID:";
cin >> Kid;
if (Kid == 0) break;
cout << endl << "Enter DATA:";
cin >> Kdata;
}
kroot = p.create(idlist,datalist,index);
p.preorder(kroot);
}
我搞定了,我用前序遍历可以了,不过,那个print()函数没有改,我注释掉了!!!谢谢!!! |
|