二叉树的链表储存结构及实现

typedef int ElemType;
struct NodeType
{
	ElemType data;
	NodeType *lch;
	NodeType *rch;
};

class BiTree
{
public:
	BiTree() { root = NULL; }
	~BiTree()
	{
		destory(root);
		root = NULL;
	}
	void creat();
	void preorder()
	{
		preorder(root);
	}
	void inorder()
	{
		inorder(root);
	}
	void postorder()
	{
		postorder(root);
	}
protected:
	NodeType *root;

private:
	void preorder(NodeType *p);			 //先根递归遍历
	void inorder(NodeType *p);			 //中根递归遍历
	void postorder(NodeType *p);		 //后根递归遍历
	void destory(NodeType *p);			 //递归删除二叉树的所有结点
};
void BiTree::destory(NodeType *p)
{

	if (p != NULL)
	{
		destory(p->lch);
		destory(p->rch);
		delete p;
	}
}

void BiTree::creat()
{
	NodeType *q, *s[20];
	ElemType x;
	int i, j;
	cout << "\n 请按照二叉树的层序,自上而下自左至右顺序组织数据" << endl;
	cout << "\n 每次输入结点的序号和数据,假设根结点值为11" << endl;
	cout << "\n 那么输入应是:1 11" << endl;
	root = NULL;
	cout << "\n i = " << endl;; cin >> i;
	cout << "\n x = " << endl; cin >> x;
	while ((i != 0) && x != 0)
	{
		q = new NodeType;					//新建一个结点
		q->data = x;						//结点数据赋值
		q->lch = NULL;						//结点的左右指针域为空
		q->rch = NULL;
		s[i] = q;							//s[i]指向该节点
		if (i == 1)root = q;
		else
		{
			j = i / 2;						//双亲结点的位置
			if (i % 2 == 0)						//偶数
				s[j]->lch = q;				//双亲结点的左指针指向该结点
			else
				s[j]->rch = q;				//双亲结点的右指针指向该结点
		}
		cout << "\n i = " << endl;; cin >> i;
		cout << "\n x = " << endl; cin >> x;
	}
}


//遍历二叉树
//1.先根递归遍历
void BiTree::preorder(NodeType *p)
{
	if (p != NULL)
	{
		cout << p->data << "" << endl;
		preorder(p->lch);  //按先根次序遍历左子树
		preorder(p->rch);  //按先根次序便利右子树
	}
}

//2.中根递归遍历
void BiTree::inorder(NodeType *p)
{
	if (p != NULL)
	{
		inorder(p->lch);
		cout << p->data << "" << endl;
		inorder(p->rch);
	}
}
//3.后根递归遍历
void BiTree::postorder(NodeType *p)
{
	if (p != NULL)
	{
		postorder(p->lch);
		postorder(p->rch);
		cout << p->data << "" << endl;
	}
}
int main()
{

	BiTree tree0;
	tree0.creat();
	cout << "\n 遍历结果为:";
	/*tree0.preorder();
	tree0.inorder();*/
	tree0.postorder();
    std::cout << "Hello World!\n"; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael.Scofield

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值