重建二叉树(前序和中序)

根据二叉树的前序输出和中序输出重建这颗二叉树

剑指offer上的一道题,

思路:前序遇到的第一个元素肯定是根节点,先建立一个根节点,然后将这个值在中序序列中查找他的位置用leftCount记录,找到后将该值左面和右边分别递归。

#include<cstdlib>
#include<cstdio>
#include<iostream>
#include<string>

using namespace std;
typedef struct node{
	int data;
	struct node * left;
	struct node * right;
	
}BTNode;
BTNode * preCreateByFrontMid(int front[],int mid[],int low,int high)
{
	if(low>=high)
		return NULL;
	
	BTNode * root=NULL;
	root=(BTNode *)malloc(sizeof(BTNode));
	root->data=front[0];
	root->left=root->right=NULL;
	
	int leftCount=0;
	for(int i=low;i<high&&front[0]!=mid[i];leftCount++,i++);
	if(low+leftCount<high)
	root->left=preCreateByFrontMid(front+1,mid,low,low+leftCount);
	if(low+leftCount+1<high)
	root->right=preCreateByFrontMid(front+leftCount+1,mid,low+leftCount+1,high);
	
	return root;
}
void midPrint(BTNode * root)
{
	if(root)
	{
		
		midPrint(root->left);
		printf("%5d",root->data);
		midPrint(root->right);
	}
}

int main(void)
{
	int n;
//	freopen("C:\\Users\\mu\\Desktop\\1.txt", "r", stdin); //文件输入到标准输入流   
	cout<<"输入节点数"<<endl; 
	cin>>n;
	int front[n],mid[n];
	cout<<"输入前序"<<endl; 
	for(int i=0;i<n;i++){
		cin>>front[i];
	}
	cout<<"输入中序"<<endl; 
	for(int i=0;i<n;i++){
		cin>>mid[i];
	}
	
	//根据前序中序重建二叉树 
	BTNode * root=NULL;
	root=preCreateByFrontMid(front,mid,0,n); 
	printf("\n");
	cout<<"输出中序:"<<endl; 
	midPrint(root);
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值