UVaOJ 112 Tree Suming

来源:互联网 发布:刷手淘搜索流量软件 编辑:程序博客网 时间:2024/06/05 23:43

题目的思路很清楚,就是建树,然后遍历就完事了。但是对于我这种新手来说,建树的操作还是有些难度的。看到那种输入的形式顿时就凌乱了。

借鉴了一下别人的处理方法。

参考博客 http://m.blog.csdn.net/blog/chuan6099/8744652

当然我是看完了别人的方法以后自己写了一遍。

#include<iostream>#include<stdlib.h>using namespace std;typedef struct Node{int data;struct Node *left,*right;}Node,*TNode;void maketree(TNode &p){int d;char c;if(cin>>d){p=(TNode)malloc(sizeof(Node));p->data=d;p->left=NULL;p->right=NULL;}else{//the input is ")"cin.clear();cin>>c;return;}cin>>c;if(c=='('){maketree(p->left);}else{cin.clear();cin>>c;}cin>>c;if(c=='('){maketree(p->right);}else{cin.clear();cin>>c;}cin>>c;return;}int dfs(TNode p,int sum,int ans){sum=sum+p->data;if((p->left==NULL)&&(p->right==NULL)){if(sum==ans)return 1;else return 0;}int tot=0;if(p->left)tot+=dfs(p->left,sum,ans);if(p->right)tot+=dfs(p->right,sum,ans);return tot;}int main(){int sum;while(cin>>sum){Node* root;char c;root=NULL;cin>>c;maketree(root);if(!root){cout<<"no"<<endl;continue;}if(dfs(root,0,sum))cout<<"yes"<<endl;else cout<<"no"<<endl;}return 0;}

输入操作的一个难点就是对于括号的处理。在这个程序中,第一个括号是在主程序中输入的。

if(c=='('){maketree(p->left);}else{cin.clear();cin>>c;}

在maketree函数里面用了一个函数叫cin.clear。这个函数的功能不是清除缓冲流,而是对于输入数据的矫正。比如本来是int型的数据,如果输入成了char,那么缓冲流中就会记录这个错误,以后就再也输入不进去数据了。所以用cin.clear进行更正。但这个时候,缓冲流中的数据并未消失,仍然存在于缓冲流中。所以再用一次cin>>c来将这个里面的数据清除掉(用cin.sync效果是一样的)。