在樹結構中,有一種特殊的二叉樹叫做排序二叉樹,直觀的理解就是——(1).每個節點中包含有一個關鍵值 (2).任意一個節點的左子樹(如果存在的話)的關鍵值小于該節點的關鍵值 (3).任意一個節點的右子樹(如果存在的話)的關鍵值大于該節點的關鍵值。現給定一組數據,請你對這組數據按給定順序建立一棵排序二叉樹,并輸出其中序遍歷的結果。
Input
輸入包含多組數據,每組數據格式如下。 第一行包含一個整數n,為關鍵值的個數,關鍵值用整數表示。(n<=1000) 第二行包含n個整數,保證每個整數在int范圍之內。 Output
為給定的數據建立排序二叉樹,并輸出其中序遍歷結果,每個輸出占一行。
Example Input
1 2 2 1 20 Example Output
2 1 20 Hint
Author
趙利強
排序二叉樹就是整個樹上左節點小于根節點,根節點小于右節點。
#include<stdio.h>#include<stdlib.h>#include<string.h>struct node{ int data; struct node *l, *r;};struct node *creat(struct node *root, int number)//建樹{ if(root == NULL) { root = (struct node *) malloc (sizeof(struct node)); root -> data = number; root -> l = NULL; root -> r = NULL; } else { if(root -> data > number) root -> l = creat(root -> l, number); else root -> r = creat(root -> r, number); } return root;};int cnt;void zhongxu(struct node *root)//中序輸出{ if(root) { zhongxu(root -> l); if(cnt == 1)//控制輸出格式 { printf("%d", root -> data); cnt++; } else printf(" %d", root -> data); zhongxu(root -> r); }}int main(){ int n, i; while(scanf("%d", &n) != EOF) { int number; cnt = 1; struct node *root = NULL;//很重要,千萬不能忘。NULL for(i = 0; i < n; i++) { scanf("%d", &number); root = creat(root, number); } zhongxu(root); printf("/n"); } return 0;}新聞熱點
疑難解答