二元排序樹

來源:互聯網
上載者:User
把二元數的所有遍曆都寫出來了,感覺二叉排序樹就更簡單啦

樹的應用:二叉排序樹
排序是一種十分重要的運算。所謂排序就是把一堆雜亂無章的元素按照某種次序排列起來,形成一個線性有序的序列。二叉排序樹是利用二叉樹的結構特點來實現對元素排序的。

一、二叉排序樹的定義

二叉排序樹或者是空樹,或者是具有如下性質的二叉樹:
  1、左子樹上所有結點的資料值均小於根結點的資料值;
  2、右子樹上所有結點的資料值均大於或等於根結點的資料值;
  3、左子樹、右子樹本身又各是一棵二叉排序樹。

由此可見,二叉排序樹是一種特殊結構的二叉樹。(18(10(3,15(12,15)),21(20,21(,37))))就是一棵二叉排序樹。

思考題1:試將上述括弧標記法表示的二叉排序樹用圖形標記法表示出來。圖
  思考題2:試用中序遍曆二叉樹的方法寫出遍曆二叉排序樹的結果,並思考二叉排序樹究竟有什麼作用?。

二、二叉排序樹的構造

二叉排序樹的構造過程實質上就是排序的過程,它是二叉排序樹作媒介,將一個任意的資料序列變成一個有序序列。二叉排序樹的構造一般是採用陸續插入結點的辦法逐步構成的。具體構造的思路是:
  1、以待排序的資料的第一個資料構成根結點;
  2、對以後的各個資料,逐個插入結點,而且規定:在插入過程的每一步,原有樹結點位置不再變動,只是將新資料的結點作為一個葉子結點插入到合適的位置,使樹中任何結點的資料與其左、右子樹結點資料之間的關係仍然符合對二叉排序樹的要求。

原始碼如下:
//暑假練習:二叉排序樹
//要求:給一組資料,按照二叉排序樹排列
//增廣賢文
//時間 :2006.8.4
#include <iostream>
using namespace std ;

typedef struct node
{
int data ;
struct node * lchild ,* rchild ;
}bitnode , * bitree ;

bitree root = NULL;

void insert(bitree &t , int value);//插入
void print(bitree t); //按照先跟順序列印排序二叉樹的建立情況
void preorder(bitree t);//先序遍曆二叉樹
void inorder(bitree t);//中序遍曆二叉樹

int main()
{
int ch = 0 ;
while(ch != -1)
{
cin>>ch ;
if(ch != -1)
insert(root,ch);
}

putchar('/n');
cout<<"插入建立的排序二元數的先序表示如下,#代表空節點 :"<<endl;
print(root);

putchar('/n');
cout<<"前序走訪二叉排序數 :";
preorder(root);

putchar('/n');
cout<<"中序遍曆二叉排序數 :";
inorder(root);

putchar('/n');
system("PAUSE");
return 0 ;
}

void insert(bitree &t , int value)
{
if(!t)
{
t = new bitnode ;
t->data = value ;
t->lchild = t->rchild = NULL ;
}
if(t->data > value)
insert(t->lchild,value);
if(t->data < value)
insert(t->rchild,value);
}

void print(bitree t)
{
if(t)
{
cout<<t->data;
print(t->lchild);
print(t->rchild);
}

else
putchar('#');

}

void preorder(bitree t)
{
if(t)
{
cout<<t->data<<" ";
preorder(t->lchild);
preorder(t->rchild);
}

}

void inorder(bitree t)
{
if(t)
{
inorder(t->lchild);
cout<<t->data<<" ";
inorder(t->rchild);
}

}

測試結果











-1

插入建立的排序二元數的先序表示如下,#表示空節點
5421##3###6#87##9##
前序走訪二叉排序樹:5 4 2 1 3 6 8 7 9
中序遍曆二叉排序樹:1 2 3 4 5 6 7 8 9

二叉排序樹的中序遍曆就是將資料從小到大,這個比線性排列顯然要好多了  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.