package tree_test;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class lsomorphic {
public static class TreeNode{
char element;
int left;
int right;
TreeNode(char element,int left,int right)
{
this.element=element;
this.left=left;
this.right=right;
}
};
@SuppressWarnings("null")
public static int BuildTree(List<TreeNode> t1) throws Exception {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt(); //总个数
int[] check=new int[n+1]; //标志位check
int i;
if(n!=0) {
for(i=0;i<=n;i++)check[i]=0;
for(i=0;i<n;i++) { //每行输入数据
String m=scanner.next();
char element=m.charAt(0);
char cl=m.charAt(1);
char cr=m.charAt(2);
TreeNode e = new TreeNode(element,-1,-1); //建立一个TreeNode
t1.add(e); //加到List里面
if(cl!='-') { //添加左右孩子节点,并把check标志位做标志
e.left=(cl-'0');
check[e.left]=1;
}
if(cr!='-') {
e.right=(cr-'0');
check[e.right]=1;
}
}
}
for(i=0;i<n;i++)
if(check[i]==0) return i; //通过标志位,找到根节点
throw new Exception("can't find root,the tree not exit ");
}
public static void printTreeNode(List<TreeNode> t1,int r1) {
System.out.print(t1.get(r1).element);
if(t1.get(r1).left!=-1)
printTreeNode(t1,t1.get(r1).left);
if(t1.get(r1).right!=-1)
printTreeNode(t1,t1.get(r1).right);
}
public static int lsomorphic(List<TreeNode> t1,int r1,List<TreeNode> t2,int r2) {
if(r1==-1 && r2==-1) //都是空树时
return 1;
if((r1==-1&&r2!=-1)||(r1!=-1&&r2==-1)) //其中一个是空树
return 0;
if(t1.get(r1).element!=t2.get(r2).element)
return 0; //根节点不同
if(t1.get(r1).left==-1 && t2.get(r2).left==-1) //都没有左子树
return(lsomorphic(t1,t1.get(r1).right,t2,t2.get(r2).right));
if((t1.get(r1).left!=-1&&t2.get(r2).left!=-1)&&(t1.get(t1.get(r1).left)).element==t2.get(t2.get(r2).left).element)
return((lsomorphic(t1,t1.get(r1).left,t2,t2.get(r2).left))&(lsomorphic(t1,t1.get(r1).right,t2,t2.get(r2).right)));
else
return(lsomorphic(t1,t1.get(r1).right,t2,t2.get(r2).left)&lsomorphic(t1,t1.get(r1).left,t2,t2.get(r2).right));
}
@SuppressWarnings("null")
public static void main(String[] args) {
// TODO Auto-generated method stub
List<TreeNode> T1 = new ArrayList<TreeNode>();
List<TreeNode> T2 = new ArrayList<TreeNode>();
int root_t1 = 0,root_t2 = 0;
try{
root_t1=BuildTree(T1);
root_t2=BuildTree(T2);
// System.out.println(T1.size()); //传递类可以改参数
// System.out.print(root_t1);
// System.out.print(root_t2);
// printTreeNode(T1,root_t1);
// printTreeNode(T2,root_t2);
}catch(Exception e) {
System.out.print("can't find root,the tree not exit ");
}
System.out.print(lsomorphic(T1,root_t1,T2,root_t2));
}
}