实现了书上这样的存储方式:
#ifndef listTree_H_
#define listTree_H_
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
struct childNode
{
int child;
childNode *next;
};
struct headNode
{
char data;
int parent;
childNode *firstChild;
};
class ListTree
{
public:
ListTree();
~ListTree();
void creat();
void preOrder();
void leverOrder();
private:
headNode*node;
int num;
};
ListTree::ListTree()
{
node=NULL;
cout<<"Please input the number of node in the tree."<<endl;
cin>>num;
}
//lever order to creat
void ListTree::creat()
{
char temp[20];
childNode *tempChild;
node=new headNode[num];
int i,j,k;
cout<<"Input every data of the tree.(level order,first is root)"<<endl;
for(i=0; i<num; i++)
{
cin>>node[i].data;
node[i].parent=-1;
node[i].firstChild=NULL;
}
getchar();
for(i=0; i<num; i++)
{
cout<<"input children of "<<node[i].data<<endl;
cin.getline(temp,20);
int len=strlen(temp);
for(j=num-1; j>=0; j--)
{
for(k=0; k<len; k++)
{
if(temp[k]==node[j].data)
{
tempChild=new childNode;
tempChild->child=j;
tempChild->next=node[i].firstChild;
node[i].firstChild=tempChild;
node[j].parent=i;
}
}
}
}
}
void ListTree::leverOrder()
{
int i;
for(i=0; i<num; i++)
{
cout<<node[i].data<<" ";
}
cout<<endl;
}
//it's so like when compare to DFS
void ListTree::preOrder()
{
bool visited[num];
memset(visited,0,sizeof(visited));
stack<int>S;
cout<<node[0].data<<" ";
visited[0]=1;
S.push(0);
while(!S.empty())
{
int top=S.top();
childNode*cur=node[top].firstChild;
while(cur)
{
if(cur && !visited[cur->child])
{
cout<<node[cur->child].data<<" ";
visited[cur->child]=1;
S.push(cur->child);
break;
}
cur=cur->next;
}
if(!cur)S.pop();
}
}
ListTree::~ListTree()
{
int i;
childNode*temp;
for(i=0; i<num; i++)
{
childNode*cur=node[i].firstChild;
while(cur)
{
temp=cur;
cur=cur->next;
delete(temp);
}
delete(&node[i]);
}
}
#endif
测试:
#include <iostream>
#include "listTree.h"
using namespace std;
int main()
{
ListTree test;
test.creat();
test.leverOrder();
cout<<endl;
test.preOrder();
return 0;
}