樹結(jié)構(gòu)練習(xí)——排序二叉樹的中序遍歷 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic PRoblem Description
在樹結(jié)構(gòu)中,有一種特殊的二叉樹叫做排序二叉樹,直觀的理解就是——(1).每個節(jié)點中包含有一個關(guān)鍵值 (2).任意一個節(jié)點的左子樹(如果存在的話)的關(guān)鍵值小于該節(jié)點的關(guān)鍵值 (3).任意一個節(jié)點的右子樹(如果存在的話)的關(guān)鍵值大于該節(jié)點的關(guān)鍵值。現(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
不想廢話了,繼續(xù)寫代碼~
#include <stdio.h>#include <stdlib.h>int p[1000],k;typedef struct node{ int data; struct node *l,*r;}node;node *creat_BinSortTree(node *root,int key)//建立二叉排序樹{ if(root){//root里面有東西的時候,就開始比較傳進(jìn)來數(shù)的大小 if(root->data > key)//如果比它大就放在左字?jǐn)?shù) root->l = creat_BinSortTree(root->l,key); else//否則就放在右子樹 root->r = creat_BinSortTree(root->r,key); } else{ root = (node *)malloc(sizeof(struct node));//如果root啥也沒有的話就給它開個內(nèi)存,然后左右子樹都賦空,并且root的值為key root->l = NULL; root->r = NULL; root->data = key; } return root;//這里要主要要搞個返回的,寫成void容易錯}void *inOrderPrint(node *root){ int i = 0; if(root){ inOrderPrint(root->l); p[k++] = root->data;//中序輸出因為要注意格式,存在數(shù)組中好搞一點 inOrderPrint(root->r); }}int main(){ int n,i; int a; while(~scanf("%d",&n)){ node *root = NULL;//這里千萬別忘記要讓初始的root被賦值為NULL for(i=0; i<n; i++){ scanf("%d",&a); root = creat_BinSortTree(root,a); } k = 0; inOrderPrint(root); printf("%d",p[0]); for(i=1; i<n; i++) printf(" %d",p[i]); printf("/n"); } return 0;}新聞熱點
疑難解答