递归统计二叉树中右孩子的个数
本题要求采用递归方式统计二叉树中右孩子结点的个数
函数接口定义:
在这里描述函数接口。例如:
int CountRightNode(BinTree bt);
其中bt是待统计的二叉树,函数返回右孩子结点的个数
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef char DataType;
typedef struct BTreeNode
{
DataType data;
struct BTreeNode *leftchild;
struct BTreeNode *rightchild;
}BinTreeNode;
typedef BinTreeNode *BinTree;
BinTree CreateBinTree_Recursion()
{
char ch;
BinTree bt;
scanf("%c", &ch);
if (ch == ‘@’)
bt = NULL;
else
{
bt = (BinTreeNode *)malloc(sizeof(BinTreeNode));
bt->data = ch;
bt->leftchild = CreateBinTree_Recursion();
bt->rightchild = CreateBinTree_Recursion();
}
return bt;
}
/* 请在这里填写答案 */
void DestroyBinTree(BinTree bt)
{
if (bt != NULL)
{
DestroyBinTree(bt->leftchild);
DestroyBinTree(bt->rightchild);
free(bt);
}
}
int main()
{
BinTree bt = NULL;
int rightcount;
bt = CreateBinTree_Recursion();
rightcount = CountRightNode(bt);
printf("%d", rightcount);
DestroyBinTree(bt);
return 0;
}
输入样例:
AB@D@@C@@
输出样例:
2
代码:
//此题是得定义个全局变量。若在函数中定义变量就只是局部变量,但每次调用递归都会将变量又初始化。也是经过此题了解到在PTA上可以在函数外定义全局变量不会报错。
int c=0;
int CountRightNode(BinTree bt){
if(bt){
if(bt->rightchild)c++;
CountRightNode(bt->leftchild);
CountRightNode(bt->rightchild);
}
return c;
}