建立一颗多叉树

//Tree.h
#pragma once
#include<iostream>
using namespace std;

template
class Tree;
template
class TreeNode
{
friend class Tree;
public:
TreeNode() :data(Type()), nextsibling(NULL), firstchild(NULL)
{}
TreeNode(Type d, TreeNode* L = NULL, TreeNode* C = NULL) :data(d), nextsibling(L), firstchild(C)
{}
~TreeNode()
{}
private:
Type      data;
TreeNode* firstchild;
TreeNode* nextsibling;
};
template
class Tree
{
public:
Tree(Type Ref) :Refvalue(Ref)
{
root = NULL;
}
public:
void create()
{
create(root);
}
void show()
{
cout << "PreOder:";
PreOder(root);
cout << endl;
}
protected:
void create(TreeNode*& t)
{
Type item;
cin>>item;
if (item == Refvalue)
{
t = NULL;
return;
}
else
{
t = new TreeNode(item);
create(t->firstchild);
create(t->nextsibling);
}
}
bool empty()
{
return root == NULL;
}
void PreOder(TreeNode*& t)
{
if (t == NULL)
return;
else
{
cout << t->data << " "; PreOder(t->firstchild);
PreOder(t->nextsibling);
}
}
private:
TreeNode* root;
Type Refvalue;
};


#include"Tree.h"
int main()
{
Tree mytree('#');
mytree.create();
mytree.show();
return 0;
}


建立一颗多叉树有很多种方法,我这里选择的是“子女-兄弟链“法,上面是实现:

这里是先序建立的//RAD#E##B#CFG#H#K#####
树的大致形态如下:





你可能感兴趣的:(建立一颗多叉树)