It is also the forward traversal of the Binary Search Tree.
1. Tree creation will affect the shape of the entire tree in sequence
2. Remember to release resources
3. You can use double pointers and reference optimizers ..
Some printf () in the Code are previously set breakpoints, which can be ignored.
[Cpp]
# Include <iostream>
Using namespace std;
Struct BST
{
Char ch;
BST * lson, * rson;
BST ()
{
Ch = 0; // impossible characters
Lson = rson = 0;
}
} * Root;
BST * insert (BST * p, char x) // 1. p does not exist; 2. p exists. 1.x= p-> ch 2.x< 3.x>
{// Printf ("x = % c p = % d \ n", x, p );;
If (p = NULL)
{
P = new BST;
P-> ch = x;
Return p;
}
// Printf ("~ ");
If (x <p-> ch) p-> lson = insert (p-> lson, x );
If (x> p-> ch) p-> rson = insert (p-> rson, x );
Return p;
}
Char RE [11]; int nRE;
Void pre_order (BST * p) // One, p has two, p does not exist
{
If (p) RE [nRE ++] = p-> ch;
// Cout <"RE =" <RE <endl;
If (p-> lson) pre_order (p-> lson );
If (p-> rson) pre_order (p-> rson );
}
Void Free (BST * p)
{
If (p-> lson) Free (p-> lson );
If (p-> rson) Free (p-> rson );
Delete p;
}
Int main ()
{
Int n, I, j, len;
Char t [11], model [11];
While (scanf ("% d", & n), n)
{
Root = 0;
Scanf ("% s", t );
Len = strlen (t );
For (I = 0; I <len; I ++) root = insert (root, t [I]);
NRE = 0; pre_order (root); RE [nRE] = '\ 0 ';
Strcpy (model, RE );
For (I = 1; I <= n; I ++)
{
BST * p = 0; // printf ("~ ");
Scanf ("% s", t); len = strlen (t); // printf ("!! % S \ n ", t );
For (j = 0; j <len; j ++) p = insert (p, t [j]);
NRE = 0; pre_order (p); RE [nRE] = '\ 0 ';
If (strcmp (model, RE) = 0) printf ("YES \ n ");
Else printf ("NO \ n ");
Free (p );
}
// Printf ("@");
Free (root );
}
Return 0;
}