1. 程式人生 > >【演算法導論】求二叉樹的葉子數和深度

【演算法導論】求二叉樹的葉子數和深度

/**********************************************\
函式功能:計算葉子節點個數
輸入:    二叉樹的根節點
輸出:    葉子節點個數
\**********************************************/
int countleaf(bitree *p)
{
	static int count=0;//注意這裡是靜態變數,也可以改為全域性變數
	if(p!=NULL)
	{
		count=countleaf(p->lchild);
		if((p->lchild==NULL)&&(p->rchild==NULL))
			count=count+1;
		count=countleaf(p->rchild);
	}
	return count;
}

 2.求二叉樹的深度
         二叉樹的深度是二叉樹中結點層次的最大值。可通過先序遍歷來計算二叉樹中每個結點的層次, 其中的最大值即為二叉樹的深度。
具體演算法如下:

/**********************************************\
函式功能:計算樹的深度
輸入:    二叉樹的根節點、當前樹的深度
輸出:    樹的深度
\**********************************************/
int treedepth(bitree*p,int l)
{
	static int h=0;
	if(p!=NULL)
	{
		l++;
		if(l>h)
			h=l;
		h=treedepth(p->lchild,l);
		h=treedepth(p->rchild,l);
	}
	return h;
}

兩者的完整例項如下:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

#define maxsize 20

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

void Layer(bitree *p);
bitree* CreatBitree(int* arrayA,int n);
int countleaf(bitree *p);
int treedepth(bitree*p,int l);

void main()
{
	int arrayA[10]={0,1,2,3,4,5,6,7,8,9};//第一個節點沒有用於儲存資料
	int n=sizeof(arrayA)/sizeof(int);
    int l=0;//二叉樹的深度
	bitree *head=NULL;

	head=CreatBitree(arrayA,n);

	printf("二叉樹的葉子數為:%d",countleaf(head));
	printf("\n");
	printf("二叉樹的深度為:  %d",treedepth(head,l));
	printf("\n");
	printf("按廣度優先搜尋遍歷的結果為:");
//	Layer(head);
	printf("\n");

}

/*************************************************\
函式功能:建立二叉樹(按照順序方式)
輸入:    原始陣列
輸出:    二叉樹的頭結點
\*************************************************/
bitree* CreatBitree(int* arrayA,int n)//順序儲存 建立二叉樹
{
	bitree *root;
	bitree *queue[maxsize];
	bitree *p;
	int front,rear;
	front=1;rear=0;
	root=NULL;

	for(int i=1;i<n;i++)
	{
		p=(bitree*)malloc(sizeof(bitree));
		p->data=arrayA[i];
		p->lchild=NULL;
		p->rchild=NULL;

		rear++;
		queue[rear]=p;

		if(rear==1)
			root=p;
		else
		{
			if(i%2==0)
				queue[front]->lchild=p;
			else
			{
				queue[front]->rchild=p;
				front=front+1;
			}
		}

	}

	return root;
}
/**********************************************\
函式功能:計算葉子節點個數
輸入:    二叉樹的根節點
輸出:    葉子節點個數
\**********************************************/
int countleaf(bitree *p)
{
	static int count=0;//注意這裡是靜態變數,也可以改為全域性變數
	if(p!=NULL)
	{
		count=countleaf(p->lchild);
		if((p->lchild==NULL)&&(p->rchild==NULL))
			count=count+1;
		count=countleaf(p->rchild);
	}
	return count;
}

/**********************************************\
函式功能:計算樹的深度
輸入:    二叉樹的根節點、當前樹的深度
輸出:    樹的深度
\**********************************************/
int treedepth(bitree*p,int l)
{
	static int h=0;
	if(p!=NULL)
	{
		l++;
		if(l>h)
			h=l;
		h=treedepth(p->lchild,l);
		h=treedepth(p->rchild,l);
	}
	return h;
}
注:如果程式出錯,可能是使用的開發平臺版本不同,請點選如下連結: 解釋說明