Topic link: https://cn.vjudge.net/contest/317394#problem/A
Judging whether two sequences are the same binary search tree sequence
Input
Beginning with a number n, (1 <= n <= 20) means there are n judgements to be made, and the input ends when n= 0.
The next line is a sequence with a length less than 10 and contains (0-9) numbers without duplicate numbers. Based on this sequence, a binary search tree can be constructed.
The next n rows have n sequences. Each sequence format is the same as the first sequence. Please determine whether the two sequences can form the same binary search tree.
Output
If the sequence is the same, YES is output, otherwise NO is output.
Sample Input
2 567432 543267 576342 0
Sample Output
YES NO
Binary Search Tree: It can efficiently manage dynamic collections.
Features: All nodes satisfy that all nodes in the left subtree are smaller than themselves, and all nodes in the right subtree are larger than themselves.
Realization of Building Trees Depending on Pointer
Code:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int n,flag; struct node/*Represents each node: the key value of each node and the left and right son's pointer*/ { int val; node *le,*re; }; node *build(node *p,int x) { if(p==NULL) { node *q=new node;/*Open up a new node*/ q->val=x; q->le=q->re=NULL;/*Both left and right son addresses of the new node are NULL*/ return q; } else { if(x<p->val) p->le=build(p->le,x); if(x>p->val) p->re=build(p->re,x); return p;/*When the left and right nodes are judged, the father's address is returned.*/ } } void check(node *root,node *tr) { if(root!=NULL&&tr!=NULL) { check(root->le,tr->le);/*Intermediate traversal*/ if(root->val!=tr->val) flag=0; check(root->re,tr->re); } else if(root!=NULL||tr!=NULL) flag=0; } int main() { while(~scanf("%d",&n)&&n) { node *root=NULL; char ch[15]; scanf("%s",ch); for(int i=0; i<strlen(ch); i++)/*First, establish a standard binary search tree*/ root=build(root,ch[i]-'0');/*Each time, it recurs from the root node down to the address of NULL, and then traces the address back to the root node.*/ for(int j=0; j<n; j++) { scanf("%s",ch); flag=1; node *tr=NULL; for(int i=0; i<strlen(ch); i++) tr=build(tr,ch[i]-'0'); check(root,tr); if(flag) printf("YES\n"); else printf("NO\n"); } } return 0; }