#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#define ElemType char
using namespace std;
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T){//先序构造一棵二叉数
char ch;
cin>>ch;
if(ch=='0') T = NULL; //'0'字符表示空树
else{
T =(BiTNode*)malloc(sizeof(BiTNode));
if(!T)
cout<<"创建失败"<<endl;
T->data = ch; //生成根结点
CreateBiTree(T->lchild); //构造左子树
CreateBiTree(T->rchild); //构造右子树
}
// return OK;
}
int maxDepth(BiTNode *root)
{
if(root == NULL)
return 0;
int res = 0;
queue<BiTNode *> q;
q.push(root);
while(!q.empty())
{
++ res;
for(int i = 0, n = q.size(); i < n; ++ i)
{
BiTNode *p = q.front();
q.pop();
if(p -> lchild != NULL)
q.push(p -> lchild);
if(p -> rchild != NULL)
q.push(p -> rchild);
}
}
return res;
}
int main(){
BiTree T;
CreateBiTree(T);
cout<<maxDepth(T);
return 0;
}
求Maximum Depth of Binary Tree 广度优先遍历算法
最新推荐文章于 2024-08-09 23:45:12 发布