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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

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

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

數據結構實驗之求二叉樹后序遍歷和層次遍歷
Description
已知一棵二叉樹的前序遍歷和中序遍歷,求二叉樹的后序遍歷和層序遍歷。

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

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

Sample
Input
2
abdegcf
dbgeafc
xnliu
lnixu
Output
dgebfca
abcdefg
linux
xnuli

/*需要好好學習一下這個層次遍歷 void cengci(node *T) {queue<node *>t;t.push(T);while(!t.empty()){T = t.front();t.pop();if(T){cout<<T->data;t.push(T->l);t.push(T->r);}} } */ ```cpp #include<bits/stdc++.h>using namespace std; typedef struct node {char data;node *l;node *r; } node; node *buildtree(int len, char *pre, char *mid) {if(!len){return NULL;}node *root;root = new(node);root->data = pre[0];int i;for(i = 0; i < len; i++){if(mid[i] == pre[0]){break;}}root->l = buildtree(i, pre + 1, mid);root->r = buildtree(len - i - 1, pre + i + 1, mid + i + 1);return root; } void postorder(node *T) {if(T != NULL){postorder(T->l);postorder(T->r);printf("%c", T->data);} } void cengci(node *T) {queue<node *>t;t.push(T);//先將樹的根節點入隊while(!t.empty())//如果隊列不空,則進入循環{T = t.front();//將隊首元素出隊t.pop();if(T)//保證進來的所有都有不為空{cout<<T->data;//輸出隊首元素;t.push(T->l);t.push(T->r);}} } int main() {int t;char pre[100], mid[100];while(~scanf("%d", &t)){while(t--){node *root;scanf("%s", pre);scanf("%s", mid);int len = strlen(pre);root = buildtree(len, pre, mid);postorder(root);printf("\n");cengci(root);printf("\n");}}return 0; }

總結

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

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