C 語言二叉搜尋樹的插入建立以及中序遍歷練習
阿新 • • 發佈:2018-11-16
1
二叉搜尋樹的層次遍歷(10分)
題目內容:
二叉搜尋樹在動態查表中有特別的用處,一個無序序列可以通過構造一棵二叉搜尋樹變成一個有序序列,
構造樹的過程即為對無序序列進行排序的過程。每次插入的新的結點都是二叉搜尋樹上新的葉子結點,在進行
插入操作時,不必移動其它結點,只需改動某個結點的指標,由空變為非空即可。
這裡,我們想探究二叉樹的建立和層次輸出。
輸入格式:
只有一行,包含若干個數字,中間用空格隔開。(數字可能會有重複,對於重複的數字,只計入一個)
輸出格式:
輸出一行,對輸入數字建立二叉搜尋樹後進行按層次周遊的結果。
輸入樣例:
51 45 59 86 45 4 15 76 60 20 61 77 62 30 2 37 13 82 19 74 2 79 79 97 33 90 11 7 29 14 50 1 96 59 91 39 34 6 72 7
輸出樣例:
51 45 59 4 50 86 2 15 76 97 1 13 20 60 77 90 11 14 19 30 61 82 96 7 29 37 62 79 91 6 33 39 74 34 72
時間限制:500ms記憶體限制:32000kb
二叉查詢樹(Binary Search Tree),(又:二叉搜尋樹,二叉排序樹)它或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別為二叉排序樹。
二叉搜尋樹的插入是個標準的遞迴演算法,中序遍歷藉助佇列完成,這裡用陣列指標模擬了一個佇列
#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode { ElementType Data; BinTree Left; BinTree Right; }; BinTree Insert(BinTree BST, ElementType X); void LevelorderTraversal(BinTree BT); int main() { BinTree BST = NULL; int temp; char c; while (1) { scanf_s("%d", &temp); BST = Insert(BST, temp); c = getchar(); if (c != ' ') break; } LevelorderTraversal(BST); system("pause"); return 0; } /* 你的程式碼將被嵌在這裡 */ BinTree Insert(BinTree BST, ElementType X) { if (!BST) { BST = (BinTree)malloc(sizeof(struct TNode)); BST->Data = X; BST->Left = BST->Right = NULL; } else { if (X < BST->Data) { BST->Left = Insert(BST->Left, X); // 遞迴插入左子樹 } else if (X > BST->Data) { BST->Right = Insert(BST->Right, X); // 遞迴插入右子樹 } } return BST; } void LevelorderTraversal(BinTree BT) { if (!BT) return; int flag = 0; // 控制輸出格式 BinTree queue[100]; BinTree temp; int front = 0, rear = 0; queue[rear++] = BT; // 當前節點入隊 while (front != rear) // 當佇列非空的情況 { temp = queue[front++]; if (!flag) { printf("%d", temp->Data); flag = 1; } else { printf(" %d", temp->Data); } if (temp->Left) queue[rear++] = temp->Left; if (temp->Right) queue[rear++] = temp->Right; } }