二叉树-已知两种遍历求第三种

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/imotolove/article/details/80641407

1,先序和中序,输出后序

#include<iostream>
#include<stack>
using namespace std;
const int N=1010;
int n,pre[N],in[N]; //先序数组和后序数组
stack<int> st;      //存放父节点
void build(int l1,int r1,int l2,int r2) //l1,r1,是先序数组,l2,r2中序数组
{   
    int i,j;
    st.push(pre[l1]);    //父节点入栈
    for(i=l2;i<=r2;i++)
        if(in[i]==pre[l1])  //找到父节点在中序遍历的位置i
            break;
    j=l1+(i-l2+1);      //确定左子树和右子树在先序遍历的分界点j,即右子树的父节点
    if(j<=r1 && i+1<=r2)    //求解右子树
        build(j,r1,i+1,r2);
    if(l1+1<=j-1 && l2<=i-1)    //求解左子树
        build(l1+1,j-1,l2,i-1);
}

int main()
{
	cin>>n;
  	for(int i=0;i<n;i++)
        cin>>pre[i];
    for(int i=0;i<n;i++)
        cin>>in[i];
    build(0,n-1,0,n-1);
    while(!st.empty())
	{
        cout<<st.top()<<" ";   
        st.pop();
    }
    return 0;
}

2,后序和中序,输出先序

#include<iostream>
#include<stack> 
using namespace std;
stack<int>p;
int bac[100],in[100];
void bfs(int l1,int r1,int l2,int r2)//l1,r1中序,l2,r2后序 
{
	cout<<bac[r2]<<" ";
	int i,j;
	for(i=l1;i<=r1;i++)
	{
		if(in[i]==bac[r2])
		break;
	} 
	j=r2-(r1-i+1);
	if(i-1>=l1&&j>=l2)
	bfs(l1,i-1,l2,j);//左子树 
	if(r1>=i+1&&r2-1>=j+1)
	bfs(i+1,r1,j+1,r2-1);//右子树 
}
int main()
{
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	cin>>bac[i];
	for(int i=0;i<n;i++)
	cin>>in[i];
	bfs(0,n-1,0,n-1);
} 
/*
8
4 6 5 2 8 7 3 1
4 2 6 5 1 8 3 7
*/


猜你喜欢

转载自blog.csdn.net/imotolove/article/details/80641407