構建一顆完全二叉搜索樹


      給出一串數,如何來構造一顆完全二叉搜索樹。我們了解完全二叉搜索樹的定義,就不多說。接下來我們需要用一種數據結構來儲存,一般使用線性表或者鏈表來儲存一顆樹,對於完全二叉樹而言,用數組儲存的優勢高於用鏈表儲存,對於線性表儲存完全二叉數,不用擔心空間的浪費,也容易操作。於是我們就選擇線性表來儲存。

對於給定的一個一組數如:1 6 2 3  4 5,我們先對數做一次排序:1 2 3 4 5 6  .我們知道對於一個給定結點個數的完全二叉樹就是一個固定形狀的二叉樹,左子樹的數都比根節點小,右子樹數都比根結點大。一旦知道左子樹的結點個數我們就可以確定根節點的位置。對於上面給出的案例,首先這棵樹的左子樹有3個結點,於是根節點是第4位,即為4.於是1 2 3是左子樹,4 5是右子樹,然后用相同的方法去處理左子樹和右子樹,可以得到求解此問題的遞歸函數。

#include<iostream>
#include<fstream>
#include<cmath>
#include<algorithm>
using namespace std;
#define max 100
class Tree{
public:
int a[max];
int last;
};
Tree*T=new Tree; //建立一顆空的二叉搜索樹
void CreateBinaryT(int p[],int left,int right,int TRoot);
int main(){
ifstream sin("a.txt");
int n,i;
int p[max];
while (sin >>n){
T->last = n;
for (i = 0; i < n; i++)
sin >> p[i];
sort(p, p + n);
CreateBinaryT(p, 0, n - 1,0); //樹的根節點在下標為0的位置開始
for (i = 0; i < T->last; i++)
cout << T->a[i] << " "; //層序輸出
cout << endl;
}
return 0;
}
int Getleftson(int n){/*此函數計算左子樹結點個數*/
int l, h, i;
for (i = 0; pow(2, i) <= n; i++);
h = i - 1;; //計算log(n+1)的下屆
l = n + 1 - pow(2, h);
if (l>pow(2, h - 1))
return pow(2, h) - 1;
else
return n - pow(2, h - 1);
}
void CreateBinaryT(int p[], int left, int right,int TRoot){
int n = right - left + 1;
if (n == 0)
return; //p中沒有元素要處理是遞歸出口
int l = Getleftson(right - left + 1); //獲得左子樹節點個數
T->a[TRoot] = p[left + l];
CreateBinaryT(p, left, left + l - 1,TRoot*2+1); //左子樹遞歸
CreateBinaryT(p, left + l + 1, right,TRoot*2+2); //右子樹遞歸
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM