用了一个二维数组作为二叉树的存储结构。数组中第i行存储结点i的左子树和右子树的下标。
解题思路:做一次遍历,检查每个结点是否是樱桃结点。
#include <bits/stdc++.h>//ASI
typedef long long ll;
using namespace std;
int t[105][2],n,m,ans=0;
void dfs(int root)
{
if(root==0)
return;
int lchild=t[root][0],rchild=t[root][1];
dfs(lchild);
dfs(rchild); //检查是否满足樱桃条件
if(lchild&&rchild&&!t[lchild][0]&&!t[lchild][1]&&!t[rchild][0]&&!t[rchild][1])
ans++;
}
int main()
{
int i,j,x,y;
string s;
cin>>n>>m;
for(i=1;i<=m;i++)
{
cin>>x>>s>>y; //存储二叉树用了一个n行2列的数组,[0]存左子树,[1]存右子树
if(s=="left")
t[x][0]=y;
else
t[x][1]=y;
}
dfs(1);
cout<<ans;
return 0;
}