#include "iostream"
using namespace std;
/************************************************************************/
/* 树的一般创建,兄弟孩子表示法¨
节点序号1 2 3 4 5 6 7 8 9 10 11 12 13
data 0 0 0 0 0 0 0 0 0 0 0 0 0
parent 0 1 2 2 1 5 6 6 1 9 9 9 12 */
/************************************************************************/
struct TreeNode {
char data;
int NodeFlag;
TreeNode * Leftmost_Child,* Right_Sibling;
};
typedef TreeNode* TPosition;
int treeMap [13][3];
int nodeNum;
queue <TPosition> nodeQueue;
void addNode();
//根据INDEX建立节点
TPosition createNode(int index)
{
TPosition temp=new TreeNode;
temp->data=treeMap[index][1];
temp->NodeFlag=treeMap[index][0];
temp->Leftmost_Child=temp->Right_Sibling=NULL;
return temp;
}
//根据父节点添加子节点
void addNodeToParent(TPosition tempP)
{
bool findFlag=false;
int i,j,k;
//判断是否是叶节点
for ( i=0;i<nodeNum;i++)
{
if (treeMap[i][2]==tempP->NodeFlag)
{
findFlag=true;
break;
}
}
//叶节点返回
if (!findFlag)
{
return;
}
//保存父节点
TPosition parentNode=tempP;
//寻找子节点
for ( i=0;i<nodeNum;i++)
{
tempP=parentNode;
if (treeMap[i][2]==tempP->NodeFlag)
{
if (tempP->Leftmost_Child==NULL)
{
tempP->Leftmost_Child=createNode(i);
addNodeToParent(tempP->Leftmost_Child);
}
else
{
tempP=tempP->Leftmost_Child;
//在节点右树的最右端,添加兄弟节点
while ((tempP->Right_Sibling)!=NULL)
{
tempP=tempP->Right_Sibling;
}
tempP->Right_Sibling=createNode(i);
addNodeToParent(tempP->Right_Sibling);
}
}
}
}
TPosition createTree()
{
int i,j,k;
TPosition root;
root=createNode(0);
TPosition tempP=root;
addNodeToParent(root);
return root;
}
int main()
{
cin>>nodeNum;
int a;
for(int j=0;j<3;j++)
{
for(int i=0;i<nodeNum;i++)
{
cin>>treeMap[i][j];
}
a++;
}
createTree();
return;
}
本文介绍了一种使用兄弟孩子表示法创建树结构的方法,并通过具体的数据结构实现了树的构建过程。利用队列和节点指针,文章详细阐述了如何根据节点间的父子及兄弟关系构造树形数据结构。
2万+

被折叠的 条评论
为什么被折叠?



