暑假集訓 8.11 樹結構練習——排序二叉樹的中序遍歷 sdutoj2128
阿新 • • 發佈:2019-01-23
樹結構練習——排序二叉樹的中序遍歷
Time Limit: 1000MS Memory limit: 65536K
題目描述
在樹結構中,有一種特殊的二叉樹叫做排序二叉樹,直觀的理解就是——(1).每個節點中包含有一個關鍵值 (2).任意一個節點的左子樹(如果存在的話)的關鍵值小於該節點的關鍵值 (3).任意一個節點的右子樹(如果存在的話)的關鍵值大於該節點的關鍵值。現給定一組資料,請你對這組資料按給定順序建立一棵排序二叉樹,並輸出其中序遍歷的結果。輸入
輸入包含多組資料,每組資料格式如下。 第一行包含一個整數n,為關鍵值的個數,關鍵值用整數表示。(n<=1000) 第二行包含n個整數,保證每個整數在int範圍之內。輸出
為給定的資料建立排序二叉樹,並輸出其中序遍歷結果,每個輸出佔一行。
示例輸入
1 2 2 1 20
示例輸出
2 1 20
///原題 後臺有bug....苦了我一上午啊....
///ACcode
#include <iostream> using namespace std; const int maxn=10010; int num[maxn]; typedef struct tree { int data; tree *lc,*rc; ///leftchildren and rightchildren } tree,*Tree; void Insert(Tree &T,int key) { if(T==NULL) ///如果T節點無資料 申請空間 將key放入 { T=new tree; T->lc=NULL; T->rc=NULL; ///設 左右孩子為空 T->data=key; return ; ///結束 此次函式 } if (key > T->data) { Insert(T->rc,key); } else ///if (key < T->data) 現在題目這地方還有bug 就是處理等於問題 { Insert(T->lc,key); ///遞迴呼叫 } } int top; ///從零開始 注意初始化 void midout(Tree &T) /// InOrder { if(T) { midout(T->lc); top++; num[top]=T->data; /// 中序輸出陣列下標從 1 開始 midout(T->rc); } } int main() { int n,i,key; Tree T; while (cin>>n) { top=0; ///初始化 0 T=NULL; ///剛開始無資料設定為空 for (i=1; i<=n; i++) { cin>>key; Insert(T,key); ///依次插入key進入排序二叉樹 } midout(T); for (i=1; i<=top; i++) { cout<<num[i]; if (i!=top) { cout<<" "; } } cout<<endl; ///控制輸出格式 } return 0; }