国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

求二叉樹的層次遍歷

2019-11-11 00:47:09
字體:
來源:轉載
供稿:網友

think: 1 通過中序遍歷和后序遍歷還原二叉樹 2 二叉樹的層序遍歷(隊列思想) sdut原題鏈接 求二叉樹的層次遍歷 Time Limit: 1000MS Memory Limit: 65536KB

PRoblem Description 已知一顆二叉樹的前序遍歷和中序遍歷,求二叉樹的層次遍歷。

Input 輸入數據有多組,輸入T,代表有T組測試數據。每組數據有兩個長度小于50的字符串,第一個字符串為前序遍歷,第二個為中序遍歷。

Output 每組輸出這顆二叉樹的層次遍歷。

Example Input 2 abc bac abdec dbeac

Example Output abc abcde

Hint

Author fmh

以下為accepted代碼

#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{ char date; struct node *left; struct node *right;}BinTree;BinTree *root, *link[54];char st1[54], st2[54];BinTree * get_build(int len, char *st1, char *st2)//建立二叉樹{ if(len == 0) return NULL; int i; BinTree *root; root = (BinTree *)malloc(sizeof(BinTree)); root->date = st1[0];//尋找根節點,新的根節點為前序遍歷st1的第一個 for(i = 0; i < len; i++)//尋找新的根節點在中序遍歷st2中的位置 { if(st2[i] == root->date) break; } root->left = get_build(i, st1+1, st2);//(左子樹的長度,左子樹在前序遍歷中的開始位置,左子樹在中序遍歷中的開始位置) root->right = get_build(len-i-1, st1+i+1, st2+i+1);//(右子樹的長度,右子樹在前序遍歷中的位置,右子樹在中序遍歷中的位置) return root;}void ans(BinTree *root)//二叉樹的層序遍歷{ if(root)///判斷root是否為NULL { int i = 0, j = 0; link[j++] = root; while(i < j) { if(link[i]) { link[j++] = link[i]->left;//入隊 link[j++] = link[i]->right;//入隊 printf("%c", link[i]->date);//層序遍歷 } i++;//出隊 } }}int main(){ int T, len; scanf("%d", &T); while(T--) { scanf("%s %s", st1, st2); len = strlen(st1); root = get_build(len, st1, st2);//調用建立二叉樹函數 ans(root);//調用二叉樹的層序遍歷函數 printf("/n"); } return 0;}/***************************************************User name: jk160630Result: AcceptedTake time: 0msTake Memory: 112KBSubmit time: 2017-02-08 08:40:58****************************************************/
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 米泉市| 鄂温| 奉新县| 两当县| 泸溪县| 岢岚县| 新乡市| 略阳县| 昔阳县| 宾川县| 蒲城县| 宣城市| 讷河市| 广平县| 观塘区| 理塘县| 广安市| 彩票| 郁南县| 嘉善县| 哈密市| 马山县| 平泉县| 嘉祥县| 龙陵县| 定襄县| 和顺县| 大宁县| 翼城县| 青龙| 马龙县| 安顺市| 长宁县| 临沂市| 翁牛特旗| 乌兰察布市| 新巴尔虎左旗| 鹿泉市| 惠来县| 顺义区| 新乐市|