已知一個按先序輸入的字符序列,如abd,,eg,,,cf,,,(其中,表示空結點)。請建立該二叉樹并按從上到下從左到右的順序輸出該二叉樹的所有葉子結點。 Input
輸入數據有多行,每一行是一個長度小于50個字符的字符串。 Output
按從上到下從左到右的順序輸出二叉樹的葉子結點。 Example Input
abd,,eg,,,cf,,, xnl,,i,,u,, Example Output
dfg uli Hint
Author
xam
這個題就是用層序遍歷的方法到達最后一層輸出
#include<stdio.h>#include<string.h>#include<stdlib.h>char a[55];int top;struct node{ int data; struct node *l, *r;};struct node *creat(){ struct node *root; top++; if(a[top] == ',') root = NULL; else { root = (struct node*) malloc(sizeof(struct node)); root -> data = a[top]; root -> l = creat(); root -> r = creat(); } return root;};void yezi(struct node *root){ int in = 0, out = 0; struct node *p[100]; p[in++] = root; while(in > out) { if(p[out]) { if(p[out] -> l == NULL && p[out] -> r == NULL)//判斷是不是葉子 printf("%c", p[out] -> data); p[in++] = p[out] -> l; p[in++] = p[out] -> r; } out++; }}int main(){ while(scanf("%s", a) != EOF) { top = -1; struct node *root; root = creat(); yezi(root); printf("/n"); } return 0;}新聞熱點
疑難解答