#include<iostream>
using namespace std;
struct BiTNode
{
char data;
BiTNode* lchild;
BiTNode* rchild;
};
typedef BiTNode * BiTree;
BiTNode * CreateBiTNode(char value)
{
BiTNode*pNode = new BiTNode();
pNode->data = value;
pNode->lchild = NULL;
pNode->rchild = NULL;
return pNode;
}
void ConnectTreeNodes(BiTNode* pParent, BiTNode* pLeft, BiTNode* pRight)
{
if (pParent != NULL)
{
pParent->lchild = pLeft;
pParent->rchild = pRight;
}
}
void PrintTreeNode(BiTNode* pNode)
{
if (pNode != NULL)
{
cout << "结点" << pNode->data << "的";
if (pNode->lchild != NULL)
cout << "左子为" << pNode->lchild->data;
else
cout << "左子为空";
if (pNode->rchild != NULL)
cout << ",右子为" << pNode->rchild->data << "." << endl;
else
cout << ",右子为空." << endl;
}
}
void PrintTree(BiTree bt)
{
PrintTreeNode(bt);
if (bt != NULL)
{
if (bt->lchild != NULL)
PrintTree(bt->lchild);
if (bt->rchild != NULL)
PrintTree(bt->rchild);
}
}
void DestoryTree(BiTree &bt)
{
if (bt != NULL)
{
BiTNode* pLeft = bt->lchild;
BiTNode* pRight = bt->rchild;
delete bt;
bt = NULL;
DestoryTree(pLeft);
DestoryTree(pRight);
}
}
int main()
{
int n, num, i, j, k;
char ch;
BiTNode **pNode;
cout << "请输入二叉树中结点的个数: ";
cin >> n;
pNode = new BiTNode *[n + 1];
pNode[0] = NULL;
cout << "请依次输入各结点的数据的元素(第1个结点输入一定为根结点):";
for (i = 1; i <= n; i++)
{
cin >> ch;
pNode[i] = CreateBiTNode(ch);
}
cout << "树中结点元素值与结点序号的对应关系如下: " << endl;
for (i = 1; i <= n; i++)
cout << pNode[i]->data << "-->" << i << " ";
cout << endl;
cout << "请输入各结点间的关系,输入时按父节点序号,左子结点序号和右子结点序号方式定义."<<endl;
cout << "若某结点不存在左子或右子结点,则子结点序号输入为0.定义关系时,每个非终端结点定义一次,叶子结点无需定义.";
cout << "q请输入树中非终端结点的数目";
cin >> num;
cout << "请按 非终端结点序号 其左子结点序号 其右子结点序号 的方式输入各非终端结点的子结点情况。" << endl;
for (n = 0; n < num; n++)
{
cin >> i >> j >> k;
ConnectTreeNodes(pNode[i], pNode[j], pNode[k]);
}
if (pNode[1] != NULL)
PrintTree(pNode[1]);
else
cout << "The binaryTree is null." << endl;
DestoryTree(pNode[1]);
delete[]
pNode;
return 0;
}
二叉树的建立
最新推荐文章于 2019-03-20 20:57:36 发布