Symmetric Binary Tree

Source: Internet
Author: User

Symmetric Binary Tree
Symmetric binary tree [Problem description] if the structure of the left and right Subtrees of a binary tree is symmetric, that is, the two Subtrees are both empty or not empty, the binary tree is symmetric. Determine whether a given binary tree is symmetric by programming. For example, if Binary Tree T1 is symmetric, T2 is asymmetric. The binary tree is given in an ordered structure. If read # Is null, the binary tree T1 = ABCDE, T2 = ABCD # E. If the binary tree is symmetric, the output is "Yes ", otherwise, "No" is output ". [Input sample] tree_c.in ABCDE [output sample] tree_c.out Yes

 1 #include<iostream> 2 using namespace std; 3 struct node 4 { 5     int parent; 6     int lchild; 7     int rchild; 8 }a[1001]; 9 int main()10 {11     char d;12     int i=1;13     while(cin>>d)14     {15         if(d=='#')16         {17             a[i/2].lchild=0;18             a[i].parent=0;19         }20         else21         {22             if(i%2==0)23             {24                 a[i/2].lchild=d;25                 a[i].parent=i/2;26             }27             else28             {29                 a[i/2].rchild=d;30                 a[i].parent=i/2;31             }32         }33         i++;34     }35     int flag=0;36     for(int j=1;j<=i;j++)37     {38         if((a[j].lchild!=0&&a[j].rchild!=0)||(a[j].lchild==0&&a[j].rchild==0))39         {40             continue;41         }42         else43         {44             flag=1;45             break;46         }47     }48     if(flag==1)49     {50         cout<<"No";51     }52     else53     {54         cout<<"Yes";55     }56     return 0;57 }

 

Test data:

Abc ## de ##### fg No
A Yes
Abcd No
Abcdefg Yes
ABC # D # E No

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.