Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 求二叉树深度,递归和非递归

1、二叉树定义typedef struct BTreeNodeElement_t_ {
    void *data;
} BTreeNodeElement_t;typedef struct BTreeNode_t_ {
    BTreeNodeElement_t *m_pElemt;
    struct BTreeNode_t_    *m_pLeft;
    struct BTreeNode_t_    *m_pRight;
} BTreeNode_t;2、求二叉树深度定义:对任意一个子树的根节点来说,它的深度=左右子树深度的最大值+1(1)递归实现如果根节点为NULL,则深度为0如果根节点不为NULL,则深度=左右子树的深度的最大值+1int  GetBTreeDepth( BTreeNode_t *pRoot)
{
    if( pRoot == NULL )
        return 0;    int lDepth = GetBTreeDepth( pRoot->m_pLeft);
    int rDepth = GetBTreeDepth( pRoot->m_pRight);    return ((( lDepth > rDepth )? lDepth: rDepth) + 1 );       
}(2)非递归实现借助队列,在进行按层遍历时,记录遍历的层数即可。int GetBTreeDepth( BTreeNode_t *pRoot){
    if( pRoot == NULL )
        return 0;    queue< BTreeNode_t *> que;
    que.push( pRoot );
    int depth = 0;
    while( !que.empty() ){
        ++depth;
        int curLevelNodesTotal = que.size();
        int cnt = 0;
        while( cnt < curLevelNodesTotal ){
            ++cnt;
            pRoot = que.front();
            que.pop();
            if( pRoot->m_pLeft )
                que.push( pRoot->m_pLeft);
            if( pRoot->m_pRight)
                que.push( pRoot->m_pRight);
        }
    }    return;
}二叉树的常见问题及其解决程序 http://www.linuxidc.com/Linux/2013-04/83661.htm【递归】二叉树的先序建立及遍历 http://www.linuxidc.com/Linux/2012-12/75608.htm在JAVA中实现的二叉树结构 http://www.linuxidc.com/Linux/2008-12/17690.htm【非递归】二叉树的建立及遍历 http://www.linuxidc.com/Linux/2012-12/75607.htm二叉树递归实现与二重指针 http://www.linuxidc.com/Linux/2013-07/87373.htm二叉树先序中序非递归算法 http://www.linuxidc.com/Linux/2014-06/102935.htm轻松搞定面试中的二叉树题目 http://www.linuxidc.com/linux/2014-07/104857.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-01/111637.htm