前序+中序--后序
二叉樹(shù)的前序、中序、后序遍歷的定義: 前序遍歷:對(duì)任一子樹(shù),先訪問(wèn)跟,然后遍歷其左子樹(shù),最后遍歷其右子樹(shù); 中序遍歷:對(duì)任一子樹(shù),先遍歷其左子樹(shù),然后訪問(wèn)根,最后遍歷其右子樹(shù); 后序遍歷:對(duì)任一子樹(shù),先遍歷其左子樹(shù),然后遍歷其右子樹(shù),最后訪問(wèn)根。 給定一棵二叉樹(shù)的前序遍歷和中序遍歷,求其后序遍歷(提示:給定前序遍歷與中序遍歷能夠唯一確定后序遍歷)。
#include <stdio.h> #include <stdlib.h> #include<cstdio> #include<algorithm> #include <iostream> #include<stack> #include <string.h> using namespace std; //1 確定根,確定左子樹(shù),確定右子樹(shù)。 //2 在左子樹(shù)中遞歸。 //3 在右子樹(shù)中遞歸。 //4 打印當(dāng)前根。 char pre[100],mid[100]; struct node{char key;node *left,*right; }Tree[50]; int loc=0; node *Creat(){Tree[loc].left=Tree[loc].right=nullptr;return &Tree[loc++]; } node *Build(int s1,int e1,int s2,int e2){node *ans=Creat();ans->key=pre[s1];int root_index;for(int i=s2;i<=e2;i++){if(mid[i]==pre[s1]){root_index=i;break;}}if(root_index!=s2){ans->left=Build(s1+1,s1+(root_index-s2),s2,root_index-1);}if(root_index!=e2){ans->right=Build(s1+(root_index-s2)+1,e1,root_index+1,e2);}return ans; } void postOrder(node *T){if(T==nullptr) return;postOrder(T->left);postOrder(T->right);printf("%c",T->key); } int main(){while(scanf("%s",pre)!=EOF){scanf("%s",mid);loc=0;int len1=strlen(pre);int len2=strlen(mid);node *T=Build(0,len1-1,0,len2-1);postOrder(T);cout<<endl;}return 0; }
轉(zhuǎn)載于:https://www.cnblogs.com/anhuixuyin218/p/9124825.html
總結(jié)
- 上一篇: 原码反码补码(转)
- 下一篇: Hashtable元素的删除