Hdustm1 Binary Search Tree

Source: Internet
Author: User

 
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.