已知二叉樹的先序遍歷序列和中序遍歷序列,輸出該二叉樹的後序遍歷序列
阿新 • • 發佈:2017-06-06
iostream code tor data- span main ast avi dsm
題目描寫敘述
輸入二叉樹的先序遍歷序列和中序遍歷序列,輸出該二叉樹的後序遍歷序列。
輸入
第一行輸入二叉樹的先序遍歷序列;
第二行輸入二叉樹的中序遍歷序列。
輸出
輸出該二叉樹的後序遍歷序列。
輸入二叉樹的先序遍歷序列和中序遍歷序列,輸出該二叉樹的後序遍歷序列。
輸入
第一行輸入二叉樹的先序遍歷序列;
第二行輸入二叉樹的中序遍歷序列。
輸出
輸出該二叉樹的後序遍歷序列。
演示樣例輸入
ABDCEF
BDAECF
演示樣例輸出
DBEFCA
#include <iostream> #include <cstring> #define MAX 50+3 using namespace std; typedef char Elem_Type; typedef struct BiTree { Elem_Type data;//數據 struct BiTree *Lchild;//左孩子 struct BiTree *Rchild;//右孩子 }BiTree; //要查找的元素 查找的地方 數組的長度 int Search_Num(Elem_Type num,Elem_Type *array,int len) { for(int i=0; i<len; i++) if(array[i] == num) return i; //return -1;//沒有找到 } //前序遍歷 中序遍歷 中序數組長度 BiTree *Resume_BiTree(Elem_Type *front,Elem_Type *center,int len) { if(len <= 0) return NULL; BiTree *temp = new BiTree; temp->data = *front; int index = Search_Num(*front,center,len); temp->Lchild = Resume_BiTree(front+1,center,index); temp->Rchild = Resume_BiTree(front+index+1,center+index+1,len-index-1); return temp; } void PostOrderTraverse(BiTree *root)//後序遍歷 { if( root != NULL) { PostOrderTraverse(root->Lchild); PostOrderTraverse(root->Rchild); cout<<root->data; } } int main(void) { Elem_Type *preorder = new Elem_Type [MAX];//前序 Elem_Type *inorder = new Elem_Type [MAX];//中序 cin>>preorder;cin>>inorder; BiTree *root = Resume_BiTree(preorder,inorder,strlen(inorder)); PostOrderTraverse(root); cout<<endl; return 0; } /************************************** Problem id : SDUT OJ 1291 User name : 李俊 Result : Accepted Take Memory : 444K Take Time : 0MS Submit Time : 2014-05-16 22:52:07 **************************************/
已知二叉樹的先序遍歷序列和中序遍歷序列,輸出該二叉樹的後序遍歷序列