树的基本操作与构建
1.节点的建立
采用struct来构建结点,每个节中存有数据(本实验存放的int)和两个指针,一个儿子指针(左结点),一个兄弟指针(其余结点)。内置初始化构造函数。
2.树类的建立,包括一个根指针(结构体指针),与一大堆函数。
3. 明确几个基本概念:
用这个树作为例子。。。。。。
这是一个普通的树,用此次程序构建后变成一个兄弟孩子表示法:
4. 树的遍历:
前序遍历(先根节点,后左孩子节点,再右孩子结点)
中序遍历(先左孩子结点,后根节点,再右孩子结点) //普通树是否存在中序遍历????
后序遍历(先左孩子节点,后右孩子结点,再根节点)
#include <iostream>
using namespace std;
struct STreeNode
{
int data;
struct STreeNode* pfirstchild;
struct STreeNode* pnextBrother;
STreeNode(int V)
{
data = V;
pfirstchild=NULL;
pnextBrother=NULL;
}
};
class CTree
{
public:
struct STreeNode* pRoot;
public:
CTree();
CTree(int V);
~CTree();
void Insert(int parentValue,int Value);
STreeNode *Search(STreeNode *pNode,int V);
void InsertBrother(STreeNode *pNode,int V);
void input();
void preoder(STreeNode *N);//前序遍历
void Inother(STreeNode *N);//中序遍历
void postorder(STreeNode *N);//后序遍历
};
void CTree::postorder(STreeNode *N)
{
if(N==NULL)
return ;
postorder(N->pfirstchild);
postorder(N->pnextBrother);
cout<<" "<<N->data<<" ";
}
void CTree::Inother(STreeNode *N)
{
if(N==NULL)
return ;
Inother(N->pfirstchild);
cout<<" "<<N->data<<" ";
Inother(N->pnextBrother);
}
void CTree::preoder(STreeNode *N)//n为根节点指针
{
if(N==NULL)
{
//cout<<"没有树的根节点"<<endl;
return ;
}
cout<<" "<<N->data<<" ";
preoder(N->pfirstchild);
preoder(N->pnextBrother);
}
void CTree::input()
{
int a,b;
while(cin>>a>>b)
{
Insert(a,b);
}
return ;
}
CTree::CTree()
{
pRoot=NULL;
}
CTree::CTree(int V)
{
pRoot = new STreeNode(V);
if ( pRoot == NULL )
return ;
}
STreeNode *CTree::Search(STreeNode *pNode,int V)
{
if(pNode == NULL)
return NULL;
if(pNode->data==V)
return pNode;
if(pNode->pfirstchild==NULL&&pNode->pnextBrother==NULL)
return NULL;
else
{
if(pNode->pfirstchild!=NULL)
{
struct STreeNode *pNodeTemp = Search(pNode->pfirstchild,V);
if(pNodeTemp!=NULL)
return pNodeTemp;
else
{
return Search( pNode->pnextBrother,V);
}
}
else return Search( pNode->pnextBrother,V);
}
}
void CTree::Insert(int parentValue,int Value)//父节点的值 子节点的值
{
if(pRoot==NULL)
{
cout<<"创建新节点失败,原因没有初始头节点"<<endl;
return ;
}
struct STreeNode *pFindNode = Search(pRoot,parentValue);
if(pFindNode==NULL)
{
cout<<"创建新节点失败,原因未找到该节点的父节点"<<endl;
return ;
}
if(pFindNode->pfirstchild==NULL)
{
pFindNode->pfirstchild = new STreeNode(Value);
return ;
}
else
{
InsertBrother(pFindNode->pfirstchild,Value);
return ;
}
}
void CTree::InsertBrother(STreeNode *pNode,int V)
{
if(pNode->pnextBrother!=NULL)
InsertBrother(pNode->pnextBrother,V);
else
{
pNode->pnextBrother = new STreeNode(V);
return ;
}
}
int main()
{
CTree* pTree = new CTree(1);
if(pTree==NULL)
{
cout<<"创建结点失败"<<endl;
return 0;
}
pTree->input();
pTree->preoder(pTree->pRoot);
cout<<endl;
pTree->Inother(pTree->pRoot);
cout<<endl;
pTree->postorder(pTree->pRoot);
system("pause");
return 0;
}
/*
1 2
1 3
1 4
1 5
1 6
1 7
4 8
5 9
5 10
6 11
6 12
6 13
10 14
10 15
*/