树的先序 中序 推后序, 后序 中序 推先序

/**
根据中序遍历 先序遍历构建 输出后序遍历
后序遍历为左右根
递归的返回条件中序遍历中 左子树和右子树

  1. 过i将中序遍历中的树分为左子树和右子树 (i为中序遍历的根节点(需要输出的结点(每棵树都是自己
    的根结点))
    2.确定左子树的start,与 end范围,同时通过先序数组找到此时的根节点(上一个根结点+1)
    3.确定右子树的start,与 end范围,
    //同时通过先序数组找到此时的根节点(上一个根结点+左结点的个数+1)(左结点的个数是i-start)
    4.重复递归,直到所有点都被遍历
    **/
#include<iostream>
using namespace std;
int pre[] = {1, 2, 3, 4, 5, 6};
int in[] =  {3, 2, 4, 1, 6, 5};
//左右根 
void post(int root,int start,int end){
     if(start > end) return ;     //递归返回条件 
     int i=start;                 //使i为start从中序遍历中的start开始遍历找到与前序遍历中确定的根节
                                  //点相同的结点 
     while(in[i]!=pre[root]) i++; //i指向的是中序遍历中的根结点(通过i将中序遍历中的树分为左子树和右子树) 
     //左子树
     post(root+1,start,i-1);
     //右子树 
     post(root+i-start+1,i+1,end);
     printf("%d ",pre[root]);
}

int main(){
    post(0,0,5);
    return 0;
}


后序遍历与中序遍历推出先序遍历:

#include<iostream>
using namespace std;
int post[] = {3, 4, 2, 6, 5, 1};
int in[] = {3, 2, 4, 1, 6, 5};
void pre(int root,int start,int end){
    if(start>end) return;
    int i=start;
    while(i <= end && in[i] != post[root] ) i++;
    printf("%d ",post[root]);
    //左子树(确定root结点(左子树的root 为此时根节点-右子树节点个数-1))(右子树节点个数为end-i) 
    pre(root-(end-i)-1,start,i-1);
    //右子树
    pre(root-1,i+1,end); 
}
int main(){
    pre(5,0,5);     
    return 0;
}

至于先序 后序 转 中序 结果不是唯一的 eg: AB BA (无法确定 B结点连着A结点左边或者右边)

关于 先序 后序 转 中序的题

猜你喜欢

转载自www.cnblogs.com/csyxdh/p/12422287.html