树的同构 java
import java.util.Scanner; //创造节点类型 class Node { String key; int left; int right; } class test { public static void main(String[] args) { Scanner sc=new Scanner(System.in); Node[] arr1=new Node[8]; Node[] arr2=new Node[8]; int head1=biuldTree(arr1, sc); int head2=biuldTree(arr2, sc); boolean result=isTonggou(arr1,head1,arr2,head2); if (result) { System.out.print("Yes"); } else { System.out.print("No"); } } public static int biuldTree(Node[] arr,Scanner sc) { int N=sc.nextInt(); String templeft; String tempright; int[] flag=new int[N]; int root=0; for (int i=0;i<N ;i++ ) { Node node=new Node(); node.key=sc.next(); templeft=sc.next(); tempright=sc.next(); arr[i]=node; if (templeft.equals("-")) { node.left=-1; } else { node.left=Integer.parseInt(templeft); flag[node.left]=1; } if (tempright.equals("-")) { node.right=-1; } else { node.right=Integer.parseInt(tempright); flag[node.right]=1; } for (int j=0;j<N ;j++ ) { if (flag[j]==0) { root=j; } } } return root; } public static boolean isTonggou(Node[] arr1,int head1,Node[] arr2,int head2) { //递归出口 if ((head1==-1) &&( head2==-1)) {return true;} if ((head1==-1) && (head2 !=-1) || (head1!=-1) && (head2==-1)) {return false;} if (!(arr1[head1].key.equals(arr2[head2].key))) {return false;} //树1和树2的左孩子都为空,判断右孩子为根节点的树是不是同构 if ((arr1[head1].left==-1) && (arr2[head2].left==-1)) { return isTonggou(arr1,arr1[head1].right, arr2, arr2[head2].right); } //如果树1的左孩子不空,树2的左孩子也不空,并且两个左孩子的key相等,那么判断以左孩子为根的树是否同构,以右孩子为根的树是否同构 if ((arr1[head1].left != -1 )&&( arr2[head2].left != -1 )&& (arr1[arr1[head1].left].key.equals((arr2[arr2[head2].left].key)) )) { return (isTonggou(arr1, arr1[head1].left,arr2, arr2[head2].left)&&(isTonggou(arr1,arr1[head1].right,arr2,arr2[head2].right))); } //如果上述都不满足,那么判断以树1的左孩子和树2的右孩子为根的树是否同构,判断以树1的右孩子和树2的左孩子为根的树是否同构 else { return (isTonggou(arr1, arr1[head1].left,arr2, arr2[head2].right)&&(isTonggou(arr1,arr1[head1].right,arr2,arr2[head2].left))); } } }
实验结果
采用结构数组来储存节点,将孩子为空标记为-1.
Yes和No前面的树分别标记两颗树的根所在的位置,是我调试时加上以便判断哪个地方出问题的。