定义队列:
#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;
}