二叉树的第一题,看大神的代码,学到了许多。理解以后。自己又写了一遍;
代码如下:
#include <iostream>
using namespace std;
bool ScanfTree(int sum,int nDest, bool *pNull)
{
int d;
char ch;
bool br = false, bNull1 = false, bNull2 = false;//br用于递归子节点的计算结果,bNull表示左右子是否为空
cin>>ch;
if(!(*pNull = ((cin>>d) == 0))){//如果读入成功
sum+=d;
br = ScanfTree(sum,nDest,&bNull1)|ScanfTree(sum,nDest,&bNull2);
if(bNull1 && bNull2)
{
br = (nDest == sum);
}
}
cin.clear();//清除节点为空时cin的错误状态
cin>>ch;//略去当前一集末尾的右括号
return br;
}
int main ()
{
bool bNull;
for(int nDest; cin>>nDest;)//输入目标值
{
cout<<(ScanfTree(0,nDest,&bNull)?"yes":"no")<<endl;//根据结果输出yes或no
}
return 0;
}