Binary Sort Tree Title description
The binary sort tree is defined as either an empty tree or a two-fork tree with the following properties: If its left subtree is not empty, the value of all nodes on the left subtree is less than the value of its root node, and 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, and its left and right subtrees are also two-fork sorting trees. Today we are going to judge whether the two sequences are the same one or two-fork sort tree
The input begins with a number n, (1<=n<=20) indicates that there are n needs to be judged, and the input ends when n= 0. The next line is a sequence, the sequence length is less than 10, contains (0~9) number, there is no repetition number, according to this sequence can construct a binary sorting tree. The next n rows have n sequences, and each sequence format is the same as the first sequence, so please determine whether the two sequences can form the same binary sort tree. (Data guarantee does not have empty tree) output sample input
21234567899876543214321567890
Sample output
NONO
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include < math.h> #include <malloc.h> #include <stack>using namespace std;struct node{struct node*left,*right; char data;}; void creat (node* &root,char c) {if (root==null) {root=new node; root->data=c; root->left=null; root->right=null; } else if (root->data>c) creat (ROOT->LEFT,C); else creat (root->right,c);} Char p[20],q[20];int a,b;void Pre (Node*tree) {if (tree!=null) {p[a++]=tree->data; Pre (TREE->LEFT); Pre (tree->right); }}void Next (Node*tree) {if (tree!=null) {next (tree->left); Next (Tree->right); q[b++]=tree->data; }}int Main () {int n,i,j; Char str1[20],str2[20]; while (scanf ("%d", &n)!=eof) {struct node*root=null; if (n==0) break; a=0;b=0; cin>>str1; for (i=0;str1[i]!= ' + '; i++) creat (Root,str1[i]); Pre (root); p[a]= ' + '; Next (Root); q[b]= ' + '; for (j=0;j<n;j++) {cin>>str2; if (strcmp (P,STR2) ==0| | strcmp (Q,STR2) ==0| | strcmp (STR1,STR2) ==0) cout<< "YES" <<endl; else cout<< "NO" <<endl; } }}
Binary sort Tree