递归与非递归求二叉链表存储的二叉树的高度

定义队列:

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#define max 500
struct queue
{
	type member[max];
	int tail,head;
};
void initqueue(queue *q)
{
	q->head=q->tail = 0;
}
void pushqueue(queue *q,type o)
{
	if (q->tail > 50)
		return;
	q->member[q->tail++] = o;
}
type popqueue(queue *q)
{
	if (q->tail == 0)
		return NULL;
	return q->member[q->head++];
}
bool isqueueemty(queue *q)
{
	return q->tail ==q->head? true : false;
}

二叉树存储结构:

typedef struct Tnode
{
	char data;
	struct Tnode *lnode;
	struct Tnode *rnode;
}Tnode;
typedef  Tnode* type;

非递归方法求二叉树高度:

int treedepth5(Tnode *root)//非递归
{
	//每次入每层最右元素时,标记,如果刚刚出队的是最右结点那么就应发出信
	//号让下次进队的结点成为下层最右孩子,因为进队的可能是左孩子或右孩子,所以进队时都应该判断,进队后将信号关闭
	//开始时最右结点是根节点
	queue *q = (queue*)malloc(sizeof(queue));
	initqueue(q);
	Tnode *r = root;
	Tnode *flag = root;
	int depth = 0;
	int biaozhi = 0;

	if (!root)
		return 0;
	pushqueue(q, r);
	do
	{
		Tnode *tem = popqueue(q);
		if (flag == tem)
		{
			depth++;//发现出队的是最右孩子,所以表名这一层存在故加1
			biaozhi = 1;
		}
		if (tem->rnode)
		{
			pushqueue(q, tem->rnode);
			if (biaozhi)
			{
				flag = tem->rnode;
				biaozhi = 0;//关掉标志
			}
		}
		if (tem->lnode)
		{
			pushqueue(q, tem->lnode);
			if (biaozhi)
			{
				flag = tem->lnode;
				biaozhi = 0;
			}
		}
	} while (!isqueueemty(q));
	return depth;
}

递归方法求二叉树高度:

int treedepth_recursion5(Tnode *root)//递归形式
{

		if (root== NULL)
			return 0;
		else
			return treedepth_recursion5(root->lnode)>treedepth_recursion5(root->rnode) ? treedepth_recursion5(root->lnode) + 1 : treedepth_recursion5(root->rnode) + 1;
	}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值