歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 求二叉樹深度,遞歸和非遞歸

求二叉樹深度,遞歸和非遞歸

日期:2017/3/1 9:34:55   编辑: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,則深度=左右子樹的深度的最大值+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;
}

二叉樹的常見問題及其解決程序 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

Copyright © Linux教程網 All Rights Reserved