栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

#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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862352.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号