pat--还原二叉树--根据后序中序输出先序

还原二叉树   (25分)

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

输入格式:

输入首先给出正整数N(≤\le50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。

输出格式:

输出为一个整数,即该二叉树的高度。

输入样例:

9
ABDFGHIEC
FDHGIBEAC

输出样例:

5

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef struct Tree{    //树的节点 
	char data;
	struct Tree *lchild;
	struct Tree *rchild;
}treenode,*tree;
tree t = NULL;
void xianzhong(char x[],char z[],int size,tree &tmp){  ///根据先序中序构造二叉树 
	if(size == 0) return;      ///注意引用的使用 
	int index = 0;
	tmp = (tree)malloc(sizeof(treenode));   ///需要为节点分配空间 
	tmp->data = *x;     ///先序的子序列的第一个元素是其根节点 
	tmp->lchild = NULL;     ///注意这里的初始化很重要 
	tmp->rchild = NULL; 
	while(index < size){    ///每次找到先序的根节点的位置 
		if(*(z+index) == *x) break;
		index++;
	}
	xianzhong(x+1,z,index,tmp->lchild);    ///构造左孩子 
	xianzhong(x+1+index,z+index+1,size-index-1,tmp->rchild);  ///构造右孩子 
}

void print(tree t){   //先序输出,调试时使用 
	if(t != NULL){
		printf("%d ",t->data);
		print(t->lchild);
		print(t->rchild);
	}
}
int high(tree t){   ///计算树的深度 
	if(!t) return 0;   
	int lh = high(t->lchild);   ///递归找到叶子,然后从叶子节点一层一层往上数 
	int rh = high(t->rchild);
	if(lh > rh) return ++lh;    ///那边高度高就在那边加1 
	return ++rh;
	
}
int main(int argc, char *argv[]) {
	int n;
	scanf("%d",&n);
	char xianxu[55];    ///先序序列 
	char zhongxu[55];   ///中序序列 
	scanf("%s%s",xianxu,zhongxu);
	xianzhong(xianxu,zhongxu,n,t);
	printf("%d\n",high(t));
	return 0;
}


根据后序和中序遍历输出先序遍历   (25分)

本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。

输入格式:

第一行给出正整数NNN(≤30\le 3030),是树中结点的个数。随后两行,每行给出NNN个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。

输出格式:

在一行中输出Preorder:以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。

输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:

Preorder: 4 1 3 2 6 5 7

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
int xian[35]; ///定义先序序列 
int k = 0;   ///给先序计数 
void houzhong(int h[],int z[],int size){
	if(size <= 0) return;
	int temp = *(h+size-1);  ///先序的根节点在后序的最后一个位置上    
	xian[k++] = temp;     
	int index = 0;
	while(index < size){      ///找到根节点在中序中的位置 
		if(*(z+index) == temp) break;
		index++;
	}
	houzhong(h,z,index);
	houzhong(h+index,z+index+1,size-index-1);
}
int main(int argc, char *argv[]) {
	int n;
	scanf("%d",&n);
	int hou[35];
	int zhong[35];
	for(int i = 0; i < n; ++i) scanf("%d",&hou[i]);
	for(int i = 0; i < n; ++i) scanf("%d",&zhong[i]);
	houzhong(hou,zhong,n);
	printf("Preorder:");
	for(int i = 0; i < n; ++i) printf(" %d",xian[i]);
	printf("\n");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/shengsikandan/article/details/51182291