二叉樹(8)----求二叉樹第K層的節點數和二叉樹第K層的葉子節點數,遞迴方式

來源:互聯網
上載者:User

標籤:二叉樹

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層的葉子節點數,遞迴方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.