樹結構練習——排序二叉樹的中序遍歷

樹結構練習——排序二叉樹的中序遍歷

Time Limit: 1000ms   Memory limit: 65536K  有疑問?點這裏^_^

題目描述

在樹結構中,有一種特殊的二叉樹叫做排序二叉樹,直觀的理解就是——(1).每個節點中包含有一個關鍵值 (2).任意一個節點的左子樹(如果存在的話)的關鍵值小於該節點的關鍵值 (3).任意一個節點的右子樹(如果存在的話)的關鍵值大於該節點的關鍵值。現給定一組數據,請你對這組數據按給定順序建立一棵排序二叉樹,並輸出其中序遍歷的結果。
 

輸入

輸入包含多組數據,每組數據格式如下。
第一行包含一個整數n,爲關鍵值的個數,關鍵值用整數表示。(n<=1000)
第二行包含n個整數,保證每個整數在int範圍之內。

輸出

爲給定的數據建立排序二叉樹,並輸出其中序遍歷結果,每個輸出佔一行。
 

示例輸入

1
2
2
1 20

示例輸出

2
1 20

提示

 

來源

 趙利強

示例程序

  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<stdlib.h>  
  4.   
  5. struct node  
  6. {  
  7.     int data;  
  8.     struct node *l, *r;  
  9. };  
  10.   
  11. int cnt;  
  12. int n;  
  13.   
  14. struct node *build(struct node *&tree, int a)  
  15. {  
  16.     if(tree==NULL)  
  17.     {  
  18.         tree=new node;  
  19.         tree->l=NULL;  
  20.         tree->r=NULL;  
  21.         tree->data=a;  
  22.     }  
  23.     else  
  24.     {  
  25.         if(a<tree->data)  
  26.             build(tree->l, a);  
  27.         else  
  28.             build(tree->r, a);  
  29.     }  
  30.     return tree;  
  31. };  
  32.   
  33. void mid(struct node *tree)  
  34. {  
  35.     if(tree)  
  36.     {  
  37.         mid(tree->l);  
  38.         if(cnt==1)  
  39.         {  
  40.             printf("%d", tree->data);  
  41.             cnt++;  
  42.         }  
  43.         else  
  44.         {  
  45.             printf(" %d", tree->data);  
  46.         }  
  47.         mid(tree->r);  
  48.     }  
  49. }  
  50.   
  51. int main()  
  52. {  
  53.     int n, x;  
  54.     while(~scanf("%d", &n))  
  55.     {  
  56.         cnt=1;  
  57.         struct node *tree=NULL;  
  58.         for(int i=0;i<n;i++)  
  59.         {  
  60.             scanf("%d", &x);  
  61.             build(tree, x);  
  62.         }  
  63.         mid(tree);  
  64.         printf("\n");  
  65.     }  
  66.     return 0;  
  67. }  
  68.   
  69.   

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章