求二叉树(二叉链表结构)的高度的三种方法

求二叉树(二叉链表结构)的高度的三种方法,第1张

#include 
#include
#include
#define maxsize 100
//二叉树的创建序列 
//ab#df###c#e##

typedef struct BiNode{
	char date;
	struct BiNode *lchild,*rchild;
}BiNode;

BiNode* CreateBiTree();
int BTDepth(BiNode *T);
int BTDepth1(BiNode *T);
int BTDepth2(BiNode *T);

int main(){
	BiNode* t = CreateBiTree();
	int most = BTDepth2(t);
	printf("%d",most);
	return 0;
}

// 借助栈后序遍历二叉树求二叉树的深度(栈达到最大高度即为树的深度) 
int BTDepth2(BiNode *T){
	if(!T) return 0;
	BiNode* stack[maxsize];
	int most = 0;
	int top = -1;
	BiNode* temp = (BiNode *)malloc(sizeof(BiNode));
	BiNode *p = temp;
	stack[++top] = T;
	while(top != -1){
		if(stack[top]->lchild && stack[top]->lchild != temp && stack[top]->rchild != temp){
			top++; 
			stack[top] = stack[top-1]->lchild;
		}
		else if(stack[top]->rchild && stack[top]->rchild != temp){
			top++;
			stack[top] = stack[top-1]->rchild;
		}
		else{ 
			if(top>most) most = top;
			temp = stack[top];
			top--;
		}
	}
	free(p);
	return most+1;	
}


//递归求二叉树的深度 
int BTDepth1(BiNode *T){
	if(!T) return 0;
	int ldep = BTDepth1(T->lchild);
	int rdep = BTDepth1(T->rchild);
	if(ldep > rdep){
		return ldep + 1;
	}
	return rdep + 1;
}
//非递归队列求二叉树深度 
int BTDepth(BiNode *T){
	if(!T) return 0;
	int front = -1, rear = -1;
	int last = 0;
	int level = 0;
	BiNode* Queue[maxsize];
	Queue[++rear] = T;
	BiNode *temp;
	while(front != rear){
		temp = Queue[++front];
		if(temp->lchild){
			Queue[++rear] = temp->lchild;
		}
		if(temp->rchild){
			Queue[++rear] = temp->rchild;
		}
		if(front == last){
			last = rear;
			level++;
		}
	}
	return level;
}
//递归方法中序创建二叉树 
BiNode* CreateBiTree(){
	BiNode *p;
	char a;
	scanf("%c",&a);
	if(a=='#')
	p=NULL;
	else{
		p=(BiNode *)malloc(sizeof(BiNode));
		p->date=a;
		p->lchild=CreateBiTree();
		p->rchild=CreateBiTree();
	}	
	return p;
}
//递归方法中序遍历二叉树 
void Traverse(BiNode *p){
	if(p==NULL){
		return;
	}
	else{
		Traverse(p->lchild);
		printf("%c",p->date);
		Traverse(p->rchild);
	}
	return;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/798977.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存