统计利用二叉树存储的森林中树的棵数
普通树及其构成的森林均可转换成相应的二叉树,反之亦然。故而可以根据相应的转换方法去统计某一二叉树对应的森林中树的棵数.相应的二叉树可利用先序递归遍历算法创建。
输入
输入为接受键盘输入的由大写英文字符和"#"字符构成的一个字符串(用于创建对应的二叉树)。
输出
输出该用例对应的二叉树表示的森林中树的棵数。
样例输入
A#B#CD###
ABC####
AB##C##
ABCD###EF##G##H##
A##B##
样例输出
3
1
2
2
1
根节点一直往右子树的方向走可以得到几个点。即为森林的棵树。
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int N=105;
int cnt;
struct tree
{
char dat;
tree *lc,*rc;
tree()
{
lc=NULL,rc=NULL;
}
}*root;
void build(tree *root,int flag)
{
char ch;
scanf("%c",&ch);
if(ch=='#')
{
root=NULL;
return;
}
if(flag)
++cnt;
root=new tree();
root->dat=ch;
build(root->lc,0);
build(root->rc,flag);
}
int main()
{
build(root,1);
printf("%d",cnt);
}