二叉树(数据结构)——利用“递归”思想实现相关算法问题
题目一

//计算一颗二叉树的所有节点的数量,可以采用递归实现
int BinaryTree_CountNode(Tnode_t *root)
{
int n1,n2; //n1用于记录左子树的节点,n2用于记录右子树的节点
//递归函数先提前写好终止条件
if (NULL == root)
{
return 0;
}
//假设采用后序遍历来计算二叉树的节点数量
n1 = BinaryTree_CountNode(root->lchild);
n2 = BinaryTree_CountNode(root->rchild);
return n1+n2+1;
}
题目二

//计算一颗二叉树的所有叶子节点的数量,可以采用递归实现
int BinaryTree_CountLeafNode(Tnode_t *root)
{
int n1,n2; //n1记录左子树叶子节点,n2记录右子树叶子结点
//1.递归函数必须提前写好终止条件
if (NULL == root)
{
//说明是空树,则直接返回0
return 0;
}
else if(root->lchild == NULL && root->rchild == NULL)
{
//说明只有一个根节点,则根节点就是叶子节点
return 1;
}
else
{
//说明是有子树的二叉树,则需要计算左子树的叶子节点和右子树的叶子节点
n1 = BinaryTree_CountLeafNode(root->lchild);
n2 = BinaryTree_CountLeafNode(root->rchild);
}
return n1+n2;
}
题目三


浙公网安备 33010602011771号