Time limit:1000ms Memory limit:65536k Topic Description Narration
The binary sort tree is defined as: or 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, 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 sort trees.
Today we are going to infer whether the two sequences are the same one or two-fork sort tree
The input starts with a number n, (1<=n<=20) indicates that there are n need to infer that the input ends when n= 0. The next line is a sequence. The sequence length is less than 10, including (0~9) number, there is no repeated 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 infer whether the two sequences can form the same binary sort tree.
(Data guarantee there will be no empty trees)
Output Demo Sample input
21234567899876543214321567890
Demo sample Output
NONO
Still a two-fork sort tree. The definition does not change and then infer whether the two trees are the same one or two-fork sort tree, I am direct DFS a first-order traversal and then see whether the first-order traversal of the two trees is the same:
#include <algorithm> #include <iostream> #include <cstring> #include <cstdlib> #include < string> #include <cctype> #include <vector> #include <cstdio> #include <cmath> #include < deque> #include <stack> #include <map> #include <set> #define LL long long#define MAXN 1010#define pp pair<int,int> #define INF 0x3f3f3f3f#define max (x x > (y))?(x): (y)) #define min (x, y) ((() > (y))? (y): (x)) using namespace std;typedef struct Node{char d;node *l,*r;} *p;int n,sb;void Insert (P &t,int x) {if (t==null) {t=new node; t->l=null; t->r=null; T->d=x;} Else{if (x<t->d) Insert (t->l,x); Elseinsert (t->r,x);}} void Dfs (P T,char *ans) {if (T) {Ans[sb++]=t->d;dfs (T->l,ans);d FS (T->r,ans);}} int main () {while (~SCANF ("%d", &n) &&n) {p Root=null;char tem[12],ans[12];scanf ('%s ', TEM); for (int i=0;i <strlen (TEM); i++) Insert (Root,tem[i]) Sb=0;dfs (Root,ans); ans[sb]= ' + '; while (n--) {p troot=null;scanf ("%s", tem) ; for (int i=0;i<strlen (TEM); i++) Insert (Troot,tem[i]); Sb=0;dfs (Troot,tem); tem[sb]= '; if (!strcmp (Ans,tem)) puts ("YES"); Elseputs ("NO");}} return 0;}
Binary sort Tree