根据先序序列和中序序列递归创建二叉树

本文介绍了一种根据先序序列和中序序列构建二叉树的方法,并提供了完整的C++实现代码。此外,还展示了如何对构建好的二叉树进行先序遍历和中序遍历。

根据先序序列和中序序列递归创建二叉树

源代码如下:

#include <iostream>
using namespace std;

//二叉树的结构
typedef struct BTNode {
	char data;
	struct BTNode *left;
	struct BTNode *right;
}BTNode;

//根据先序序列和中序序列递归创建二叉树
BTNode * BTCreate(char a[],char b[],int n) {
	int k;
	if (n==0) {
		return NULL;
	}
	    int root = a[0];
		BTNode *BT = (BTNode *)malloc(sizeof(BTNode));	
		BT->data = root;   //树根的值可以确定了

		for (k = 0; k < n;k++) {                  //在b中查找b[k]=root的根节点
			if (b[k]==root) {
				break;
			}
		}
		BT->left = BTCreate(a+1,b,k);               //递归创建左子树
		BT->right= BTCreate(a+k+1,b+k+1,n-k-1);        //递归创建右子树
	return BT;


}


//对二叉树进行先序遍历
void PreOrder(BTNode *BTNode)
{
	if (BTNode == NULL)
		return;
	cout << BTNode->data <<" ";
	
	PreOrder(BTNode->left); //递归调用,先序遍历左子树 
	PreOrder(BTNode->right); //递归调用,先序遍历右子树 
	
}

//对二叉树进行中序遍历
void InOrder(BTNode *BTNode)
{
	if (BTNode == NULL)
		return;
	InOrder(BTNode->left); //递归调用,中序遍历左子树 
	cout << BTNode->data <<" ";
	InOrder(BTNode->right); //递归调用,中序遍历右子树 
}





int main() {
	int n=0;
	cout << "请输入序列个数" << endl;
	cin >> n;
	
	char *a = new char[n];
	cout << "请输入先序序列" << endl;
	for (int i = 0; i < n;i++) {
		cin >> a[i];
	}
	
	char *b = new char[n];
	cout << "请输入中序序列" << endl;
	for (int i = 0; i < n; i++) {
		cin >> b[i];
	}

	BTNode *BT =NULL;
	BT=BTCreate(a,b,n);
	cout << "先序遍历序列为:" << endl;
	PreOrder(BT);
	cout << endl;
	cout << "中序遍历序列为:" << endl;
	InOrder(BT);
	cout << endl;


	system("pause");
	return 0;

}

输出:

请输入序列个数
8
请输入先序序列
a b d g c e f h
请输入中序序列
d g b a e c h f
先序遍历序列为:
a b d g c e f h
中序遍历序列为:
d g b a e c h f
请按任意键继续. . .

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值