think: 1建立排序二叉樹時 注意重復元素 sdut原題鏈接 樹結構練習——排序二叉樹的中序遍歷 Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 在樹結構中,有一種特殊的二叉樹叫做排序二叉樹,直觀的理解就是——(1).每個節點中包含有一個關鍵值 (2).任意一個節點的左子樹(如果存在的話)的關鍵值小于該節點的關鍵值 (3).任意一個節點的右子樹(如果存在的話)的關鍵值大于該節點的關鍵值?,F給定一組數據,請你對這組數據按給定順序建立一棵排序二叉樹,并輸出其中序遍歷的結果。
Input 輸入包含多組數據,每組數據格式如下。 第一行包含一個整數n,為關鍵值的個數,關鍵值用整數表示。(n<=1000) 第二行包含n個整數,保證每個整數在int范圍之內。
Output 為給定的數據建立排序二叉樹,并輸出其中序遍歷結果,每個輸出占一行。
Example Input 1 2 2 1 20
Example Output 2 1 20
Hint 1 注意重復元素 Author 趙利強
以下為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) /* 若原樹為空,生成并返回一個結點的二叉搜索樹*/ { 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****************************************************/新聞熱點
疑難解答