日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

sdut 2137 数据结构实验之求二叉树后序遍历和层次遍历

發布時間:2025/4/16 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 sdut 2137 数据结构实验之求二叉树后序遍历和层次遍历 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據結構實驗之求二叉樹后序遍歷和層次遍歷

Time Limit:?1000MS?Memory Limit:?65536KB Submit?Statistic?Discuss

Problem Description

?已知一棵二叉樹的前序遍歷和中序遍歷,求二叉樹的后序遍歷和層序遍歷。

Input

?輸入數據有多組,第一行是一個整數t (t<1000),代表有t組測試數據。每組包括兩個長度小于50 的字符串,第一個字符串表示二叉樹的先序遍歷序列,第二個字符串表示二叉樹的中序遍歷序列。

Output

每組第一行輸出二叉樹的后序遍歷序列,第二行輸出二叉樹的層次遍歷序列。

Example Input

2 abdegcf dbgeafc xnliu lnixu

Example Output

dgebfca abcdefg linux xnuli

Hint

Author

#include <iostream> #include <string.h> #include <queue> #include <stack> #include <malloc.h> using namespace std; char pre[51],in[51]; typedef struct btree {char date;btree *lchild,*rchild; }btree; btree *root; btree *createbtree(char pre[],char in[],int n) {btree *b;for(int i=0;i<n;++i){if(in[i]==pre[0]){b=(btree*)malloc(sizeof(btree));b->date=pre[0];b->lchild=createbtree(pre+1,in,i);b->rchild=createbtree(pre+i+1,in+i+1,n-i-1);return b;}}return NULL; } void postbtree()//非遞歸 {stack<btree *>Stack;btree *p=root;do{while(p!=NULL){Stack.push(p);p=p->lchild;}bool flag=true;btree *r=NULL;while(!Stack.empty()&&flag){p=Stack.top();if(p->rchild==r){Stack.pop();cout<<p->date;r=p;}else{flag=false;p=p->rchild;}}}while(!Stack.empty());cout<<endl; } void levelorder() {btree *b=root;queue<btree*>Queue;Queue.push(b);while(!Queue.empty()){b=Queue.front();Queue.pop();//這個沒有返回值cout<<b->date;if(b->lchild!=NULL)Queue.push(b->lchild);if(b->rchild!=NULL)Queue.push(b->rchild);}cout<<endl; } int main() {int n;cin>>n;while(n--){cin>>pre>>in;root=(btree *)malloc(sizeof(btree));root=createbtree(pre,in,strlen(pre));postbtree();levelorder();}return 0; }后序的遍歷時對應的遞歸代碼(main函數和postorder函數: void postbtree(btree *root)//遞歸 {btree *b=root;if(b!=NULL){postbtree(b->lchild);postbtree(b->rchild);cout<<b->date;} } int main() {int n;cin>>n;while(n--){cin>>pre>>in;root=(btree *)malloc(sizeof(btree));root=createbtree(pre,in,strlen(pre));postbtree(root);cout<<endl;levelorder();}return 0; }

總結

以上是生活随笔為你收集整理的sdut 2137 数据结构实验之求二叉树后序遍历和层次遍历的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。