首页 / 操作系统 / 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)递归方式
如果给定节点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)非递归方式在遍历二叉树时,判断当前访问的节点是不是叶子节点,然后对叶子节点求和即可。前序、中序、后序、按层遍历均可。二叉树的常见问题及其解决程序 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本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-01/111640.htm