#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef struct bnode
{
char data;
struct bnode *lchild,*rchild;
}BNode,*bitree;
bitree pre_create()//创建二叉树
{
bitree bt;
char ch;
ch=getchar();
if(ch==' ')
return NULL;
else
{
bt=new BNode[sizeof(BNode)];
bt->data=ch;
bt->lchild=pre_create();
bt->rchild=pre_create();
}
}
int depth_Recursive(bitree bt)//递归算法
{
int ldepth,rdepth;
if(bt)
return depth_Recursive(bt->lchild)>depth_Recursive(bt->rchild)?(depth_Recursive(bt->lchild)+1):(depth_Recursive(bt->rchild)+1);
return 0;
}
int depth_Non_recursive(bitree bt)//利用队列进行非递归算法
{
queue<bitree> q;
bitree p=bt;
int level=0,len;
if(!bt)
return 0;
q.push(p);
while(!q.empty())//每次只有把在同一层的所有结点出队以后才level++,因此要知道当前队列的长度,用len表示
{
level++;
len=q.size();//当前队列长度就代表这一层的结点个数
while(len--)
{
p=q.front();
q.pop();
if(p->lchild)
q.push(p->lchild);
if(p->rchild)
q.push(p->rchild);
}
}
return level;
}
int main()
{
bitree bt=pre_create();
cout<<"递归算法结果:"<<endl;
cout<<depth_Recursive(bt)<<endl;
cout<<"非递归算法结果:"<<endl;
cout<<depth_Non_recursive(bt)<<endl;
}
