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