二叉树的实现

二叉树的实现

要求:

1.采用二叉链表的方式进行存储

2.构造一个二叉树类

实现以下算法:

1.创建二叉树

2.对二叉树进行前序、中序、后序遍历

输入

扩展的前序序列.在一棵树处理结束后,根据响应判断是否处理下一棵树

输出

前序、中序、后序

 

样例输入

ab##c##
Y
abc####
N

样例输出

abc
bac
bca
abc
cba
cba

源代码:

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
struct BiNode
{
	char data;
	BiNode* rchild, * lchilld;
};

class BiTree
{
public:
	BiTree() { root = Creat(); }
	void Preorder() { preorder(root); }
	void Inorder() { inorder(root); }
	void Postorder() { postorder(root); }
	BiNode* getroot();
private:
	BiNode* root;
	BiNode* Creat();
	void preorder(BiNode* bt);
	void inorder(BiNode* bt);
	void postorder(BiNode* bt);
};

BiNode* BiTree::getroot() { return root; }
void BiTree::preorder(BiNode* bt)
{
	if (bt == nullptr) return;
	else {
		cout << bt->data;
		preorder(bt->lchilld);
		preorder(bt->rchild);
	}
}

void BiTree::inorder(BiNode* bt)
{
	if (bt == nullptr) return;
	else {
		inorder(bt->lchilld);
		cout << bt->data;
		inorder(bt->rchild);
	}
}

void BiTree::postorder(BiNode* bt) {
	if (bt == nullptr) return;
	else {
		postorder(bt->lchilld);
		postorder(bt->rchild);
		cout << bt->data;
	}
}

BiNode* BiTree::Creat()
{
	BiNode* bt = nullptr;
	char ch; cin >> ch;
	if (ch == '#') bt = nullptr;
	else {
		bt = new BiNode;
		bt->data = ch;
		bt->lchilld = Creat();
		bt->rchild = Creat();
	}
	return bt;
}


int main()
{
	char a = 'Y';
	while (a == 'Y') {
		BiTree T;
		T.Preorder();
		cout << endl;
		T.Inorder();
		cout << endl;
		T.Postorder();
		cout << endl;
		cin >> a;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值