think: 1通過(guò)前序遍歷和中序遍歷還原二叉樹(shù)以及后序遍歷 2 通過(guò)已還原的二叉樹(shù)進(jìn)行層序遍歷 sdut原題鏈接 數(shù)據(jù)結(jié)構(gòu)實(shí)驗(yàn)之求二叉樹(shù)后序遍歷和層次遍歷 Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 已知一棵二叉樹(shù)的前序遍歷和中序遍歷,求二叉樹(shù)的后序遍歷和層序遍歷。
Input 輸入數(shù)據(jù)有多組,第一行是一個(gè)整數(shù)t (t<1000),代表有t組測(cè)試數(shù)據(jù)。每組包括兩個(gè)長(zhǎng)度小于50 的字符串,第一個(gè)字符串表示二叉樹(shù)的先序遍歷序列,第二個(gè)字符串表示二叉樹(shù)的中序遍歷序列。
Output 每組第一行輸出二叉樹(shù)的后序遍歷序列,第二行輸出二叉樹(shù)的層次遍歷序列。
Example Input 2 abdegcf dbgeafc xnliu lnixu
Example Output dgebfca abcdefg linux xnuli
Hint
Author ma6174
以下為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)//二叉樹(shù)的還原與后序遍歷{ if(len == 0) return NULL; int i; BinTree *root; root = (BinTree *)malloc(sizeof(BinTree)); root->date = st1[0];//尋找根節(jié)點(diǎn),新的根節(jié)點(diǎn)為前序遍歷st1的第一個(gè) for(i = 0; i < len; i++)//尋找新的根節(jié)點(diǎn)在中序遍st2中的位置 { if(st2[i] == root->date) break; } root->left = get_build(i, st1+1, st2);//(左子樹(shù)的長(zhǎng)度,左子樹(shù)在前序遍歷st1中的開(kāi)始位置,左子樹(shù)在中序遍歷st2中的開(kāi)始位置) root->right = get_build(len-i-1, st1+i+1, st2+i+1);//(右子樹(shù)的長(zhǎng)度,右子樹(shù)在前序遍歷st1中的開(kāi)始位置,右子樹(shù)在中序遍歷st2中的開(kāi)始位置) printf("%c", root->date);//后序遍歷 return root;}void ans(BinTree *root)//二叉樹(shù)的層序遍歷{ if(root)///判斷root是否為NULL { int i = 0, j = 0; link[j++] = root; while(i < j) { if(link[i])//判斷l(xiāng)ink[i]是否為NULL { link[j++] = link[i]->left;//入隊(duì) link[j++] = link[i]->right;//入隊(duì) printf("%c", link[i]->date);//層序遍歷 } i++;//出隊(duì) } }}int main(){ int T, len; scanf("%d", &T); while(T--) { scanf("%s %s", st1, st2); len = strlen(st1); root = get_build(len, st1, st2);//調(diào)用二叉樹(shù)的還原與后序遍歷函數(shù) printf("/n"); ans(root);//調(diào)用二叉樹(shù)的層序遍歷函數(shù) printf("/n"); } return 0;}/***************************************************User name: jk160630Result: AcceptedTake time: 0msTake Memory: 112KBSubmit time: 2017-02-08 09:14:45****************************************************/新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注