码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-12-04 17:55:15      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   os   sp   on   2014   log   ef   

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


#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;
}


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

标签:blog   io   ar   os   sp   on   2014   log   ef   

原文地址:http://blog.csdn.net/u013351484/article/details/41727337

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!