트리의 전체 구현 - 반복 - 적용

2552 단어
//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;
}

좋은 웹페이지 즐겨찾기