根据后序和中序输出先序

根据后序和中序输出先序

#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
using namespace std;
typedef struct Node{
    
    
	int data;
	struct Node *left,*right;
}Node,*Tree;
Tree create(int n,int *aft,int *mid){
    
    //创建树,递归就完了
	if(n==0){
    
    
		return NULL;
	}
    Tree tree=(Tree)malloc(sizeof(Node));
    tree->data=aft[n-1];//找到根节点
    tree->left=tree->right=NULL;
    int i;
    for( i=0;mid[i]!=aft[n-1];i++);
    tree->left=create(i,aft,mid);//找到左子树
    tree->right=create(n-1-i,aft+i,mid+i+1);//找到右子树
    return tree;//返回树
}
void xian(Tree tree){
    
    
	if(tree){
    
    
		cout<<tree->data<<" ";
		xian(tree->left);
		xian(tree->right);
	}
}
int main() {
    
    
	ios::sync_with_stdio(false);
	int n;
	cin>>n;
	int aft[n],mid[n];
	for(int i=0;i<n;i++){
    
    
		cin>>aft[i];//后续
	}
	for(int i=0;i<n;i++){
    
    
		cin>>mid[i];//中序
	}
	Tree tree=create(n,aft,mid);
	xian(tree);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45962741/article/details/113447218