天天看點

(資料結構)以二叉連結清單作存儲結構,設計求二叉樹高度的算法。

#include <stdio.h>
#include <stdlib.h>
#define DATATYPE char
#define NULL '\0'

typedef struct node
{
	DATATYPE data;
	struct node *lchild,*rchild;
}BTLINK;
BTLINK *creat()
{
	BTLINK *q;
	BTLINK *s[30];
	int j,i;
	char x;
	printf("i,x=");
	scanf("%d,%c",&i,&x);
	while(i!=0&&x!='$')
	{
		q=(BTLINK *)malloc(sizeof(BTLINK));
		q->data=x;
		q->rchild=NULL;
		q->lchild=NULL;
		s[i]=q;
		if(i!=1)
		{
			j=i/2;
			if(i%2==0)
				s[j]->lchild=q;
			else
				s[j]->rchild=q;
				
		}
		printf("i,x=");
		scanf("%d,%c",&i,&x);
		return s[1];  
	}
}

int depthtree(BTLINK *bt)
{
	int dep,depl,depr;
	if(bt=NULL)
		dep=0;
	else
	{
		depl=depthtree(bt->lchild);
		depr=depthtree(bt->rchild);
		if(depl>depr)
			dep=depl+1;
		else
			dep=depr+1;
	}
	return dep;
}

int main(int argc, char *argv[]) 
{
	BTLINK *bt;
	int treeh;
	bt=creat();
	treeh=depthtree(bt);
	printf("\n 二叉樹高度是%d",treeh);
	return 0;
}








           

繼續閱讀