求Maximum Depth of Binary Tree 广度优先遍历算法

来源:互联网 发布:sqllite接受数据 编辑:程序博客网 时间:2024/06/11 07:01
#include<iostream>#include<stdio.h>#include<stdlib.h>#include<queue>#define ElemType charusing 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;} 

0 0