u011415955的專欄
阿新 • • 發佈:2018-12-31
- 題目描述:
-
輸入一系列整數,建立二叉排序數,並進行前序,中序,後序遍歷。
- 輸入:
-
輸入第一行包括一個整數n(1<=n<=100)。
接下來的一行包括n個整數。
- 輸出:
-
可能有多組測試資料,對於每組資料,將題目所給資料建立一個二叉排序樹,並對二叉排序樹進行前序、中序和後序遍歷。
每種遍歷結果輸出一行。每行最後一個數據之後有一個空格。
- 樣例輸入:
-
5 1 6 5 9 8
- 樣例輸出:
-
1 6 5 9 8 1 5 6 8 9 5 8 9 6 1
- 提示:
-
輸入中可能有重複元素,但是輸出的二叉樹遍歷序列中重複元素不用輸出。
-
#include<stdio.h> struct Node { Node * lChild; Node * rChild; int data; }tree[101]; //靜態陣列分配記憶體空間, 可以不用考慮動態記憶體的申請和釋放 int alloc; Node *createNode() { tree[alloc].lChild=tree[alloc].rChild=NULL; return &tree[alloc++]; } Node* insert(Node *T,int data) //遞迴插入資料,每次都要返回根節點 { if(T==NULL) { T=createNode(); T->data=data; return T; } else if(T->data>data) T->lChild=insert(T->lChild,data); else if(T->data<data) T->rChild=insert(T->rChild,data); return T; } void pre_order(Node *root) { if(root) { printf("%d ",root->data); pre_order(root->lChild); pre_order(root->rChild); } } void in_order(Node *root) { if(root->lChild!=NULL) in_order(root->lChild); printf("%d ",root->data); if(root->rChild!=NULL) in_order(root->rChild); } void post_order(Node *root) { if(root->lChild!=NULL) post_order(root->lChild); if(root->rChild!=NULL) post_order(root->rChild); printf("%d ",root->data); } int main() { int n,i,data; while(scanf("%d",&n)!=EOF) { Node *T=NULL; alloc=0; for(i=0;i<n;i++) { scanf("%d",&data); T=insert(T,data); } pre_order(T); printf("\n"); in_order(T); printf("\n"); post_order(T); printf("\n"); } return 0; }