Binary sorting tree
Binary sorting tree Time Limit: 1000 MS Memory limit: 65536 K Description
The binary sorting tree is defined as an empty tree or a binary tree of the following properties: if its left subtree is not empty, the value of all nodes on the left subtree is smaller than the value of its root node. If its right subtree is not empty, the value of all nodes on the right subtree is greater than the value of its root node. Its left and right subtree are also binary sorting trees. Today, we need to determine whether the two sequences are in the same binary sorting tree.
The input starts with n, (1 <= n <= 20) indicates that there are n to be judged, and the input ends when n = 0. The next row is a sequence with a length less than 10 and contains (0 ~ 9). There are no repeated numbers. Based on this sequence, a binary sorting tree can be constructed. The next n rows have n sequences. The format of each sequence is the same as that of the first sequence. Determine whether the two sequences can form the same binary decision tree. (Data guarantee will not be empty tree) output sample input
21234567899876543214321567890
Sample output
NONO
Prompt source sample program
Create a binary sorting tree, and then compare the first traversal of the two
#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{ int data; struct node *l,*r;};int cnt;struct node *creat(struct node *&root,int a){ if(root==NULL) { root=(struct node *)malloc(sizeof(struct node)); root->l=NULL; root->r=NULL; root->data=a; } else { if(a<root->data) creat(root->l,a); else creat(root->r,a); }};void qianxu(struct node *root,char *str){ if(root) { str[cnt++]=root->data; qianxu(root->l,str); qianxu(root->r,str); }}int main(){ int n,i; char str1[20],str2[20]; while(~scanf("%d",&n)) { if(n==0) break; scanf("%s",str1); int len=strlen(str1); struct node *root=NULL; cnt=0; for(i=0;i<len;i++) { creat(root,str1[i]); } qianxu(root,str1); str1[cnt]='\0'; while(n--) { struct node *p=NULL; scanf("%s",str2); int len1=strlen(str2); cnt=0; for(i=0;i<len1;i++) { creat(p,str2[i]); } qianxu(p,str2); str2[cnt]='\0'; if(strcmp(str1,str2)==0) printf("YES\n"); else printf("NO\n"); } } return 0;}