linux递归深度,求二叉树深度,递归和非递归

本文介绍了二叉树的定义及两种求解二叉树深度的方法:递归与非递归方式。递归方法通过左右子树深度比较得出,非递归方法则利用队列进行按层遍历并记录层数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值