西电复试之——真题2009D 已知先序中序序列,求二叉树的后序序列

西电复试之——真题2009D 已知先序中序序列,求二叉树的后序序列

测试用例
先序:ABDGCEFH
后序:DGBAECHF
输出:GDBEHFCA

#include<iostream>
#include<string.h>
#include<string>

using namespace std;
struct node {
	int data;
	node* lchild;
	node* rchild;
};
int a[10], b[10];//先中后
int n;//结点个数
node* create(int al, int ar, int bl, int br) {
	if (al > ar) {
		//先序序列长度小于等于0时
		return NULL;
	}
	//创建一个新的结点,用来存放当前二叉树的根节点
	node* root = new node;
	//新结点的数据域为根结点的值
	root->data = a[al];
	int k;
	//在中序中找到a[al]同数据的结点
	for (k = bl; k <= br; k++) {
		if (b[k] == a[al]) {
			break;
		}
	}
	//左子树的结点个数
	int numleft = k - bl;
	root->lchild = create(al + 1, al + numleft, bl, k - 1);
	root->rchild = create(al + numleft + 1, ar, k + 1, br);
	return root;
}
void houxu(node* root) {
	if (root == NULL) {
		return;
	}
	houxu(root->lchild);
	houxu(root->rchild);
	printf("%c", root->data + 'A');
}
int main() {
	string str1, str2;
	cin >> str1 >> str2;
	n = str1.length();
	for (int i = 0; i < str1.length(); i++) {
		a[i] = str1[i] - 'A';
		b[i] = str2[i] - 'A';
	}
	node* root;
	//构建出二叉树
	root=create(0, n - 1, 0, n - 1);
	//后序遍历
	houxu(root);
	return 0;
}
原创文章 35 获赞 17 访问量 1256

猜你喜欢

转载自blog.csdn.net/qq_41436493/article/details/105807329
今日推荐