The idea of the topic is very clear, is to build, and then traverse the finished. But for me the novice, the achievement of the operation is still somewhat difficult. See that kind of input form immediately messy.
Draw on someone else's handling methods.
Reference Blog http://m.blog.csdn.net/blog/chuan6099/8744652
Of course I have read the other people's way after I wrote it again.
#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;
}
One difficulty with the input operation is the handling of parentheses. In this program, the first bracket is entered in the main program.
if (c== ' (') {
maketree (p->left);
}
else{
cin.clear ();
cin>>c;
}
In the Maketree function, a function called cin.clear is used. The function of this function is not to clear the buffer stream, but to correct the input data. For example, if the data is int type, if the input into char, then the buffer stream will record this error, and then no longer enter the data. So use cin.clear to make corrections. But this time, the data in the buffer stream does not disappear and still exists in the buffer stream. So use a cin>>c to get rid of this data (the Cin.sync effect is the same).