算法训练 求先序排列 (建树版)

  算法训练 求先序排列  
时间限制:1.0s   内存限制:256.0MB
      
问题描述
  给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。
输入格式
  两行,每行一个字符串,分别表示中序和后序排列
输出格式
  一个字符串,表示所求先序排列

   样例输入
  BADC
  BDCA
样例输出

ABCD

/*
中序遍历:左根右
后序遍历:左右根
根据后序遍历从后往前找出根节点,最后面的就是根节点,然后到中序遍历里面找根节点 
根节点左边是左子树,根节点右边是右子树
接着递归建立左右子树 
*/
#include<bits/stdc++.h>
using namespace std;
struct node{
	char ch;
	struct node *left;
	struct node *right;
};
string nex,mid;
int cnt;
struct node*build(int l1,int r1,int l2,int r2){
	if(l1 > r1||l2 > r2){
		return NULL;
	}

	char temp = nex[r2];
	int index = l1;
	while(index <= r1&&temp != mid[index]){
		index++;
	}
		
	struct node *tree = new node();
	tree->ch = temp;
	cout<<tree->ch;
	tree->left = build(l1,index - 1,l2,l2+index-l1-1);
	tree->right = build(index+1,r1,l2+index-l1,r2-1);
	return tree;
} 
void print(struct node * root){
	while(root != NULL){
		if(cnt != 0){
			printf(" %c",root->ch);
		}else{
			printf("%c",root->ch);
		}
		print(root->left);
		print(root->right);
	}
}
int main(){
//	freopen("input.txt","r",stdin);
	struct node *root = NULL;
	cin>>mid>>nex;
	root = build(0,mid.size()-1,0,nex.size()-1);
	cnt = 0;
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值