C++西电复试机试---2009ProblemD

这段代码展示了如何通过先序和中序序列构建二叉树,并进行后序遍历。它定义了一个树节点结构,然后实现了一个递归的建树函数`build`和后序遍历函数`postorder`。在主函数`main`中,程序读取多组输入数据,为每组数据构建二叉树并输出其后序序列。
摘要由CSDN通过智能技术生成

题目描述:

已知某二叉树的先序序列和中序序列,编程计算并输出该二叉树的后序序列。


输入输出:

有多组数据,每组分为两行输入,第一行表示指定二叉树的先序序列,第二行表示该二叉树的中序序列,序列元素均为大写英文字符,表示二叉树的结点。
对于每组数组,在一行上输出该二叉树的后序序列。

代码(c++):

#include<iostream>
#include<string>
using namespace std;

typedef struct Tree {
	char ch;
	Tree* lchild;
	Tree* rchild;
	Tree(char ch) :ch(ch) {}
}Tree;

// 建树
Tree* build(string prior, string inorder) {
	if (prior.length() == 0) 
		return NULL;
	char ch = prior[0];
	Tree* root = new Tree(ch);
	int index = inorder.find(ch);
	root->lchild = build(prior.substr(1, index), inorder.substr(0, index));
	root->rchild = build(prior.substr(index + 1), inorder.substr(index + 1));
	return root;
}
// 后序遍历
void postorder(Tree* root) {
	if (root == NULL) return;
	postorder(root->lchild);
	postorder(root->rchild);
	cout << root->ch;
}

int main() {
	string prior, inorder;
	while (cin >> prior >> inorder) {
		Tree* root = build(prior, inorder);
		postorder(root);
		cout << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值