设为首页 加入收藏

TOP

求二叉树深度,递归和非递归
2015-02-02 14:15:39 来源: 作者: 【 】 浏览:16
Tags:深度

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,则深度=左右子树的深度的最大值+1


int? 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;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇遍历二叉树的各种操作(非递归遍.. 下一篇求二叉树节点数,递归与非递归

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: