树的完整实现--遍历--应用

//Tree.h
#pragma once
#include<iostream>
#include<queue>
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 PreOder()
{
cout << "PreOder:";
PreOder(root);
cout << endl;
}
void PostOder()
{
cout << "PostOder:";
PostOder(root);
cout << endl;
}
void LevelOder()
{
cout << "LevelOder:";
LevelOder(root);
cout << endl;
}
void TreeNodeNum()
{
cout << "TreeNode:";
cout << TreeNodeNum(root) << endl;
}
void DeepTree()
{
cout << "TreeDeep:";
cout << DeepTree(root) << 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);
}
}
void PostOder(TreeNode*& t)
{
if (t == NULL)
return;
else
{
TreeNode *q = NULL;
for (q = t->firstchild; q != NULL; q = q->nextsibling)
PostOder(q);
cout << t->data << " ";
}
}
void LevelOder(TreeNode* t)
{
if (t != NULL)
{
queue<TreeNode* > Q;
Q.push(t);
while (!Q.empty())
{
t = Q.front();
Q.pop();
cout << t->data << " "; for (t = t->firstchild; t != NULL; t = t->nextsibling)
Q.push(t);
}
}
}
int TreeNodeNum(TreeNode* t)const //先根
{
if (t == NULL)
return 0;
int count = 1;
count += TreeNodeNum(t->firstchild);
count += TreeNodeNum(t->nextsibling);
return count;
}
int DeepTree(TreeNode* t)const //后根
{
if (t == NULL)
return 0;
int f_deep = DeepTree(t->firstchild) + 1;
int n_deep = DeepTree(t->nextsibling);
return (f_deep > n_deep ? f_deep : n_deep);
}
private:
TreeNode* root;
Type Refvalue;
};


#include"Tree.h"
int main()
{
Tree mytree('#');
mytree.create(); //创建,先根
mytree.PreOder(); //先根遍历
mytree.PostOder(); //后根遍历
mytree.LevelOder(); //层序遍历
mytree.TreeNodeNum(); //树的节点数
mytree.DeepTree(); //树的深度
return 0;
}

你可能感兴趣的:(树的完整实现--遍历--应用)