1. 程式人生 > >求二叉樹的深度(遞迴演算法+非遞迴演算法)

求二叉樹的深度(遞迴演算法+非遞迴演算法)

#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;
}