国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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

2019-11-08 18:33:04
字體:
來源:轉載
供稿:網友

PRoblem Description

在樹結構中,有一種特殊的二叉樹叫做排序二叉樹,直觀的理解就是——(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;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 许昌县| 稻城县| 内江市| 肥城市| 措勤县| 射洪县| 红原县| 佛冈县| 新昌县| 柘城县| 巫溪县| 古浪县| 松桃| 华阴市| 疏附县| 类乌齐县| 苍溪县| 磐石市| 师宗县| 新宁县| 社会| 肥城市| 丰都县| 疏勒县| 怀柔区| 洮南市| 南康市| 南溪县| 涪陵区| 伊通| 上杭县| 呼玛县| 兴和县| 西宁市| 凉城县| 石渠县| 祥云县| 吉木萨尔县| 麻栗坡县| 吴旗县| 禄丰县|