二叉树的建立

#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;

	}

	 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值