think: 1建立排序二叉樹時 注意重復(fù)元素 sdut原題鏈接 樹結(jié)構(gòu)練習(xí)——排序二叉樹的中序遍歷 Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 在樹結(jié)構(gòu)中,有一種特殊的二叉樹叫做排序二叉樹,直觀的理解就是——(1).每個節(jié)點中包含有一個關(guān)鍵值 (2).任意一個節(jié)點的左子樹(如果存在的話)的關(guān)鍵值小于該節(jié)點的關(guān)鍵值 (3).任意一個節(jié)點的右子樹(如果存在的話)的關(guān)鍵值大于該節(jié)點的關(guān)鍵值?,F(xiàn)給定一組數(shù)據(jù),請你對這組數(shù)據(jù)按給定順序建立一棵排序二叉樹,并輸出其中序遍歷的結(jié)果。
Input 輸入包含多組數(shù)據(jù),每組數(shù)據(jù)格式如下。 第一行包含一個整數(shù)n,為關(guān)鍵值的個數(shù),關(guān)鍵值用整數(shù)表示。(n<=1000) 第二行包含n個整數(shù),保證每個整數(shù)在int范圍之內(nèi)。
Output 為給定的數(shù)據(jù)建立排序二叉樹,并輸出其中序遍歷結(jié)果,每個輸出占一行。
Example Input 1 2 2 1 20
Example Output 2 1 20
Hint 1 注意重復(fù)元素 Author 趙利強(qiáng)
以下為accepted代碼
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{ int date; struct node *left; struct node *right;} BinTree;int flag, n, a[1400];BinTree * Insert(BinTree *rt, int x)//二叉搜索樹的建立算法{ if(!rt) /* 若原樹為空,生成并返回一個結(jié)點的二叉搜索樹*/ { rt = (BinTree *)malloc(sizeof(BinTree)); rt->date = x; rt->left = rt->right = NULL; } else /* 開始找要插入元素的位置*/ { if(x < rt->date) rt->left = Insert(rt->left, x);//遞歸插入左子樹 ///else if(x > rt->date)/*wrong answer*/ else rt->right = Insert(rt->right, x);//遞歸插入右子樹 } return rt;}void mid_put(BinTree *rt)//中序遍歷算法{ if(rt) { mid_put(rt->left);//左子樹遞歸 a[flag++] = rt->date; mid_put(rt->right);//右子樹遞歸 }}int main(){ int i, x; while(scanf("%d", &n) != EOF) { if(n > 0) { BinTree *root = NULL; flag = 0; for(i = 0; i < n; i++) { scanf("%d", &x); root = Insert(root, x); } mid_put(root); for(i = 0; i < flag; i++) { printf("%d%c", a[i], i == flag-1? '/n': ' '); } } } return 0;}/***************************************************User name: jk160630Result: AcceptedTake time: 0msTake Memory: 128KBSubmit time: 2017-02-08 17:07:08****************************************************/新聞熱點
疑難解答