这个题如何输入是个难点,我一开始就觉得要用递归但是不知道怎么写,看了大牛的递归恍然大悟,在输入一个左括号之后再输入int a,如果输入的是右括号就输入错误,那个cin.good()的值就变为1,cin.clear()是用来清除输入错误,也就是把cin.good()置1。其实好多题目就是这样,想通了很简单,没想通觉得好复杂,如果有更加优化的算法,求各位师兄分享经验。
AC代码
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<string.h>
using namespace std;
bool flag = false;
class node
{
public:
node* lchlid;
node* rchild;
};
node* treesum(int n,int sum)
{
int a;
char ch;
node* root;
cin>>ch;//左括号
cin>>a;
if(cin.good())
{
sum += a;
root = new node;
root->lchlid = treesum(n,sum);
root->rchild = treesum(n,sum);
if(!flag && root->lchlid == NULL && root->rchild == NULL)
if(n == sum)
flag = true;
cin>>ch;//右括号
return root;
}
else
{
cin.clear();//清楚错误状态
cin>>ch;
return NULL;
}
}
int main()
{
// freopen("input.txt","r",stdin);
int n;
while(cin>>n)
{
flag = false;
treesum(n,0);
if(flag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}
本文介绍了一种使用递归方法构建二叉树的算法,并通过一个具体的编程实例进行了演示。该方法在输入左括号后接收整数,若接收到右括号则判断为输入错误并进行错误处理。文章还提供了完整的AC代码供读者参考。

1871

被折叠的 条评论
为什么被折叠?



