資料結構實驗之二叉樹七:葉子問題
阿新 • • 發佈:2018-12-20
Problem Description
已知一個按先序輸入的字元序列,如abd,eg,cf,(其中,表示空結點)。請建立該二叉樹並按從上到下從左到右的順序輸出該二叉樹的所有葉子結點。 Input
輸入資料有多行,每一行是一個長度小於50個字元的字串。 Output
按從上到下從左到右的順序輸出二叉樹的葉子結點。 Sample Input
abd,eg,cf, xnl,i,u, Sample Output
dfg uli
#include <stdio.h> #include <stdlib.h> struct node { char data; struct node * l; struct node * r; }; char a[100]; int n; struct node * create() { struct node * root; if(a[n] == ',') { n++; root = NULL; } else { root = (struct node * )malloc(sizeof(struct node)); root->data = a[n]; n++; root->l= create(); root->r= create(); } return root; }; void yezi(struct node * root) { struct node * t[100]; int in = 0, out = 0; t[in] = root; in++; while(in > out) { if(t[out]) { if(t[out]->l==NULL&&t[out]->r==NULL) { printf("%c",t[out]->data); } if(t[out]->l!=NULL) { t[in++] = t[out]->l; } if(t[out]->r!=NULL) { t[in++] = t[out]->r; } } out++; } } int main() { struct node * root; while(scanf("%s",a)!=EOF) { n= 0; root = create(); yezi(root); printf("\n"); } return 0; }