sdut原題鏈接
數據結構實驗之二叉樹五:層序遍歷 Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 已知一個按先序輸入的字符序列,如abd,,eg,,,cf,,,(其中,表示空結點)。請建立二叉樹并求二叉樹的層次遍歷序列。
Input 輸入數據有多行,第一行是一個整數t (t<1000),代表有t行測試數據。每行是一個長度小于50個字符的字符串。
Output 輸出二叉樹的層次遍歷序列。
Example Input 2 abd,,eg,,,cf,,, xnl,,i,,u,,
Example Output abcdefg xnuli
Hint
Author xam
以下為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 s[54];int flag;BinTree * creat()//建立二叉樹函數{ BinTree * root; if(s[flag++] == ',') root = NULL; else { root = (BinTree *)malloc(sizeof(BinTree)); root->date = s[flag-1]; root->left = creat(); root->right = creat(); } return root;}void ans(BinTree *root)//二叉樹的層序遍歷函數{ if(root) { 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; scanf("%d", &T); while(T--) { flag = 0; scanf("%s", s); root = creat();//調用建立二叉樹函數 ans(root);//調用二叉樹的層序遍歷函數 printf("/n"); } return 0;}/***************************************************User name: jk160630Result: AcceptedTake time: 0msTake Memory: 120KBSubmit time: 2017-02-07 21:36:35****************************************************/新聞熱點
疑難解答