7-1 根據後序和中序遍歷輸出先序遍歷 (25 分)
阿新 • • 發佈:2018-12-19
本題要求根據給定的一棵二叉樹的後序遍歷和中序遍歷結果,輸出該樹的先序遍歷結果。
輸入格式:
第一行給出正整數N(≤30),是樹中結點的個數。隨後兩行,每行給出N個整數,分別對應後序遍歷和中序遍歷結果,數字間以空格分隔。題目保證輸入正確對應一棵二叉樹。
輸出格式:
在一行中輸出Preorder:
以及該樹的先序遍歷結果。數字間有1個空格,行末不得有多餘空格。
輸入樣例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
輸出樣例:
Preorder: 4 1 3 2 6 5 7
#include <stdio.h> #include <stdlib.h> #define maxn 1000 typedef char ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; }; int n,post[maxn],in[maxn]; BinTree CreatBinTree(int n,int *in,int *post) { BinTree temp; if(n<=0) return NULL; temp=(TNode*) malloc(sizeof(TNode)); temp->Data=post[n-1]; temp->Left=NULL; temp->Right=NULL; int i; for(i=0;i<n;i++) { if(post[n-1]==in[i]) break; } temp->Left=CreatBinTree(i,in,post); //遞迴遍歷當前根節點的左側,長度變為i; temp->Right=CreatBinTree(n-i-1,in+i+1,post+i); //右側,長度變為n-(i+1),*in從第(i+1)個位置開始,*post從第(i)個位置開始 /**下一次肯定不會再去選當前根節點吧,那麼必須排除掉; *當前根節點在in中是第i個位置,而在post中是第n-1個位置 **/ return temp; } void PreorderTraversal(BinTree BT) { if(BT == NULL) return; printf(" %d", BT->Data); PreorderTraversal(BT->Left); PreorderTraversal(BT->Right); } int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&post[i]); for(int i=0;i<n;i++) scanf("%d",&in[i]); BinTree BT=CreatBinTree(n,in,post); printf("Preorder:"); PreorderTraversal(BT); printf("\n"); return 0; }