標籤:二叉樹
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、求二叉樹第K層的節點數
(1)遞迴方式
給定根節點pRoot:
如果pRoot為空白,或者層數KthLevel <= 0,則為空白樹或者不合要求,則返回0;
如果pRoot不為空白,且此時層數KthLevel==1,則此時pRoot為第K層節點之一,則返回1;
如果pRoot不為空白,且此時層數KthLevel > 1,則此時需要求pRoot左子樹(KthLevel - 1 )層節點數和pRoot右子樹(KthLevel-1)層節點數;
int GetBTreeKthLevelNodesTotal( BTreeNode_t *pRoot, int KthLevel){ if( pRoot == NULL || KthLevel <= 0 ) return 0; if( pRoot != NULL && KthLevel == 1 ) return 1; return (GetBTreeKthLevelNodesTotal( pRoot->m_pLeft, KthLevel-1) + GetBTreeKthLevelNodesTotal( pRoot->m_pRight, KthLevel - 1 ) );}
3、求二叉樹第K層葉子節點數
(1)遞迴方式
給定節點pRoot:
如果pRoot為空白,或者層數KthLevel <= 0, 則為空白樹或者是層數非法,則返回0;
如果pRoot不為空白,且此時層數KthLevel==1時,需要判斷是否為葉子節點:
如果pRoot左右子樹均為空白,則pRoot為第K層葉子節點之一,則返回1;
如果pRoot左右子樹之一存在,則pRoot不是葉子節點,則返回0;
如果pRoot不為空白,且此時層數KthLevel > 1,需要返回 KthLevel-1層的左子樹和右子樹結點數。
int GetBTreeKthLevelLeafNodesTotal( BTreeNode_t *pRoot, int KthLevel){ if( pRoot == NULL || KthLevel <= 0 ) return 0; if( pRoot != NULL && KthLevel == 1 ){ if( pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL ) return 1; else return 0; } return ( GetBTreeKthLevelLeafNodesTotal( pRoot->m_pLeft, KthLevel - 1) + GetBTreeKthLevelLeafNodesTotal( pRoot->m_pRight, KthLevel -1) );}
二叉樹(8)----求二叉樹第K層的節點數和二叉樹第K層的葉子節點數,遞迴方式