數據結構總結(樹和二叉樹)續

一,二叉樹的算法

 1,求節點個數

   可以用遍歷,遍歷幾個就是幾個。另一種是遞歸,結點=左子樹結點+右子樹結點+1。

int count(BiNode *  root){
	int number=0;

	if (root==NULL)
		number=0;
	else
		number=count(root->lchild)+count(root->rchild)+1;
	return number;
}

 2,葉子結點數目

  遍歷到葉子節點數目加一。或者遞歸左子樹葉加右子樹葉

//遍歷
void  countleaf(BiNode *  root){
	if (root) {
		if (root->lchild==NULL && root->rchild==NULL)
			leafcount=leafcount+1;
		else
		{
			countleaf(root->lchild);
			countleaf(root->rchild);
		}
	}
	return;
}
//遞歸
int leafcount(BiNode *  root){
	int number=0;

	if (root==NULL)
		number=0;
	else if(root->lchild==NULL && root->rchild==NULL)
		number=1;
	else
	    number=leafcount(root->lchild)+leafcount(root->rchild);
	return number;
}

3,樹高

max(左子樹高度,右子樹高度)+1

int btree::shugao(bnode *bt){
    int i=0;
    if(bt==NULL) return 0;
    else{
i=max(shugao(bt->lchild),shugao(bt->rchild))+1;


    }
return i;

}

4,樹的寬度

層次遍歷可實現,運用隊列

struct q_element{ BiNode*root int level;};
int BiTree::Width(){
	queue< struct q_element > q;
	int num[100]={0,1};
	q_element s,child;
	BiNode *root;
	root=this->root;
	if(root==NULL)
		return 0;
	s.root=root;	s.level=1;	q.push(s);	
	while(!q.empty())	{
		s=q.front();
		if(s.root->lchild){
			num[s.level+1]++;
			child.root=s.root->lchild;
			child.level=s.level+1;
			q.push(child);
		}
if(s.root->rchild)	{
			num[s.level+1]++;
			child.root=s.root->rchild;
			child.level=s.level+1;
			q.push(child);
		}
		q.pop();
	}
	int max=0,i=1;
	while(num[i]>0){
		if(max<num[i])
			max=num[i];
		i++;
	}
	
	return max;
}

二,二叉樹的轉換

樹轉二叉樹:兄弟變兒子

森林轉換爲二叉樹

⑴ 將森林中的每棵樹轉換成二叉樹;

⑵ 從第二棵二叉樹開始,

  依次把後一棵二叉樹的根結點作爲前一棵二叉樹根結點的右孩子,

  當所有二叉樹連起來後,此時所得到的二叉樹就是由森林轉換得到的樹二叉樹

三,最優二叉樹與哈夫曼編碼

二叉樹的帶權路徑長度:設二叉樹具有n個帶權值的葉子結點,從根結點到各個葉子結點的路徑長度與相應葉子結點權值的乘積之和。wpl

哈夫曼樹:只有度爲0與度爲2的結點

哈夫曼編碼是前綴編碼,保證解碼時不會出現多種可能,是不等長編碼,左0右1或左1右0

四,線索二叉樹

線索:將二叉鏈表中的空指針域指向前驅結點和後繼結點的指針被稱爲線索;

線索化:使二叉鏈表中結點的空鏈域存放其前驅或後繼信息的過程稱爲線索化;

線索二叉樹:加上線索的二叉樹稱爲線索二叉樹

struct ThrNode
{
     T data;
     ThrNode<T>  *lchild, *rchild;
     flag ltag, rtag;              //標誌表示是否孩子結點處存的是真孩子
};


函數設置形參root和全局變量pre,分別表示要處理的樹的根結點和其前驅結點
如果root!=NULL
中序線索化root的左子樹
中序線索化root本身
如果root->lchild==NULL
 root->left=pre,root->ltag=1;
如果root->rchild==NULL,root->rtag=1,
如果pre!=NULL, 並且pre->rtag=1,
pre->rchild=root,;
pre=root
中序線索化root的右子樹

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章