首页 > 代码库 > 二叉树给出两种遍历序列(含中序遍历)创建一颗先序遍历二叉树

二叉树给出两种遍历序列(含中序遍历)创建一颗先序遍历二叉树

没有测试太多的例子,不知正确性怎样。。。


#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#define ms(x,y) memset(x,y,sizeof(x))
const int MAXN=1000+10;
const int INF=1<<30;
using namespace std;

struct Node
{
	char ch;
	Node *left, *right;
};

//给出先序遍历和中序遍历创建先序二叉树
void BuildTree1(Node *&root, int n, char const *pre, char const *mid)
{
	if(n <= 0) return;//子树长度为0

	root = (Node *)malloc(sizeof(Node));
	root->ch = *pre;
	root->left = NULL;
	root->right = NULL;

	const char *p = strchr(mid, *pre);//头结点在中序遍历顺序中的位置
	int k = p - mid;//左子树的长度
	BuildTree1(root->left, k, pre+1, mid);
	BuildTree1(root->right, n-1-k, pre+k+1, mid+k+1);
}

//给出后序遍历和中序遍历创建先序二叉树
void BuildTree2(Node *&root, int n, char const *post, char const *mid)
{
	if(n <= 0) return;//子树长度为0

	root = (Node *)malloc(sizeof(Node));
	root->ch = *post;
	root->left = NULL;
	root->right = NULL;

	const char *p = strchr(mid, *post);//头结点在中序遍历顺序中的位置
	int k = p - mid;//左子树的长度
	BuildTree2(root->right, n-1-k, post-1, mid+k+1);
	BuildTree2(root->left, k, post-(n-1-k)-1, mid);
}

void PreOrder(Node *root)  
{  
    if(root == NULL) return;  
    printf("%c", root->ch);  
    PreOrder(root->left);  
    PreOrder(root->right);  
}  

int main()
{
	freopen("in.txt","r",stdin);
	char pre[100], mid[100], post[100];
#if 0
	scanf("%s%s", pre, mid);
#endif
	scanf("%s%s", post, mid);
#if 0
	Node *root;
	int len = strlen(pre);
	BuildTree1(root, len, pre, mid);
#endif

	Node *root;
	int len = strlen(post);
	BuildTree2(root, len, post+len-1, mid);

	PreOrder(root);
	printf("\n");
	return 0;
}


二叉树给出两种遍历序列(含中序遍历)创建一颗先序遍历二叉树