根据前序中序求后序

本文介绍如何根据给定的前序和中序遍历序列构造二叉树,并实现后序遍历输出。通过递归算法解析序列,逐步构建二叉树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理解说(摘自百度)


如前序 为 ABDECGF
   中序 为 BDACGEF
先 根据前序第一个节点 把中序分为BD和CGEF两部分,A为根节点,A左边为左子树,右边为右子树。再把左右子树分别做上述步骤。
以此类推 根据第二,第三...个节点构成二叉树  A
                                                                      B      E
D C F
                                                                           G    B
再根据后序的性质得到DBGCBFEA
知道后序中序 求前序类似。
知道后序前序,无法求得中序。

下面两种都可以


node* getroot(int pre[],int mid[],int n){
    if(n == 0) return 0;  
     node *p = new node;  
     p->value = pre[0];  
     int i;  
     for(i=0;i<n;i++)  
    {  
         if(mid[i] == pre[0]) break;  
     }  
     p->left = getroot(pre+1,mid,i);  
     p->right = getroot(pre+i+1 ,mid+i+1,n-i-1);  
     return p;  

}


#include <iostream>
#include <string>
#include <cstring>

using namespace std;

struct node{
	char ch;
	node* left;
	node* right;
	node(){
		left=NULL;
		right=NULL;
	}
};

void getroot(string s1,string s2,node* &n){
	int len1=s1.length();
	int len2=s2.length();
	n->left=new node();
	n->right=new node();
	if(len1==0||len2==0){
		n=NULL;
		return ;
	}
	 
	string new_s11,new_s12,new_s2,new_s3;
	n->ch=s1[0];
	int j=0;
	for(j=0;  j < len2; ++j){
		if(s2[j]==s1[0]) break;
		new_s2+=s2[j];
	}
	j++;
	for(; j < len2; ++j)
		new_s3+=s2[j];
	for(j=1; j < len1; ++j){
		if(new_s3.find(s1[j])!=string::npos) break;
		new_s11+=s1[j];
	} 
	for(; j < len1; ++j)
		new_s12+=s1[j];
	//cout << new_s11+" 1" << endl << new_s12+" 1"  << endl << new_s2+" 1" << endl << new_s3+" 1" << endl << endl;
	getroot(new_s11,new_s2,n->left);
	getroot(new_s12,new_s3,n->right);
}

void pos_tra(node *n){
	if(n==NULL) return;
	pos_tra(n->left);
	pos_tra(n->right);
	cout << n->ch;
}

int main()
{
	node* n=new node();
	string s1="abdgcefh";
	string s2="dgbaechf";
	getroot(s1,s2,n);
	pos_tra(n);
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值