设为首页 加入收藏

TOP

求二叉树叶子节点个数,递归和非递归
2015-02-02 14:15:33 来源: 作者: 【 】 浏览:8
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)递归方式
如果给定节点pRoot为NULL,则是空树,叶子节点为0,返回0;
如果给定节点pRoot左右子树均为NULL,则是叶子节点,且叶子节点数为1,返回1;
如果给定节点pRoot左右子树不都为NULL,则不是叶子节点,以pRoot为根节点的子树叶子节点数=pRoot左子树叶子节点数+pRoot右子树叶子节点数


int? GetBTreeLeafNodesTotal( BTreeNode_t *pRoot)
{
? ? if( pRoot == NULL )
? ? ? ? return 0;
? ? if( pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL )
? ? ? ? return 1;


? ? return ( GetBTreeLeafNodesTotal( pRoot->m_pLeft) + GetBTreeLeafNodesTotal( pRoot->m_pRight) );
}


(2)非递归方式


在遍历二叉树时,判断当前访问的节点是不是叶子节点,然后对叶子节点求和即可。


前序、中序、后序、按层遍历均可。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇按层遍历二叉树 下一篇求二叉树第K层的节点数和二叉树第..

评论

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