數據結構上機測試4.1:二叉樹的遍歷與應用1 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic PRoblem Description
輸入二叉樹的先序遍歷序列和中序遍歷序列,輸出該二叉樹的后序遍歷序列。 Input
第一行輸入二叉樹的先序遍歷序列; 第二行輸入二叉樹的中序遍歷序列。 Output
輸出該二叉樹的后序遍歷序列。 Example Input
ABDCEF BDAECF Example Output
DBEFCA Hint
Author
#include<stdio.h>#include<stdlib.h>#include<string.h>struct node{ int data; struct node *l, *r;};struct node *creat(int n, char *a, char *b)//二叉樹的重建與后續遍歷輸出{ int i; struct node *root; if(n == 0) return NULL; root = (struct node *) malloc (sizeof(struct node)); root -> data = a[0];//找到根節點,根節點為str1(先序序列)的第一個 for(i = 0; i < n; i++) { if(b[i] == a[0]) break; } root -> l = creat(i, a+1, b);//(左子樹的長度,左子樹在str1中開始位置的地址,左子樹在str2中開始位置的地址) root -> r = creat(n - 1 - i, a+i+1, b+i+1);//(右子樹的長度,右子樹在str1中開始位置的地址,右子樹在str2中開始位置的地址) printf("%c", root -> data);//后序遍歷輸出 return root;};int main(){ char a[11111]; char b[11111]; int n; scanf("%s%s", a, b); n = strlen(a); creat(n, a, b); printf("/n"); return 0;}哇,說實話,二叉樹搞得我頭皮發麻,很難受,很氣。
新聞熱點
疑難解答