求二叉树的深度算法


算法的思想:

  采用二叉树的后序遍历非递归算法。由于后序遍历非递归算法使用一个栈实现,每次都会在一条路径上走到最底层才向上访问,再向右访问。因此,记录下栈在遍历中的最大值,即为二叉树的最大深度。

#include <iostream>
#include <stack>
using namespace std;
typedef struct BinTree
{
    int data;
    BinTree *lc;
    BinTree *rc;
}BTNode,*BinTree;
int max(int a,int b)
{
    return (a>b)?a:b;
}

int BinTreeDepth(BinTree T)
{
    stack<BinTree> s;
    BinTree p = T,r = NULL;
    int depth=0;
    while(p||!s.empty())
    {
        if(p)
        {    //从根节点向左边走
            s.push(p);
            int size = s.size();//获取栈的大小
            depth = max(depth,size);//替换最大值
            p = p->lc;
        }
        else
        {    //左边走不通向右走
            p = s.top();
            if(p->rc&&p->rc!=r)//如果右子树存在,且未被访问过
            {
                p = p->rc;
                s.push(p);
                int size = s.size();//获取栈的大小
                depth = max(depth,size);//替换最大值
                p = p->lc;
            }else
            {
                p=s.top();
                s.pop();
                cout<<p->data<<endl;
                r=p;            //记录最近访问的节点
                p=NULL;            //节点访问完之后,重置p指针,目的是为了防止再次将左孩子压栈
            }
        }
    }
    return depth;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM