class TreeNode {
int left;
int right;
String value;
}
public class Main {
/*
输入:
8
A 1 2
B 3 4
C 5 -
D - -
E 6 -
G 7 -
F - -
H - -
8
G - 4
B 7 6
F - -
A 5 1
H - -
C 0 -
D - -
E 2 -
*/
private static final int MAX_SIZE = 10;
public static void main(String[] args) {
TreeNode[] t1 = new TreeNode[MAX_SIZE];
TreeNode[] t2 = new TreeNode[MAX_SIZE];
int root1 = buildTree(t1);
int root2 = buildTree(t2);
System.out.println(isomorphism(root1, root2, t1, t2) ? "Yes":"No");
}
/**
* 静态链表-构建二叉树
* @param t1
* @return 根节点所在的索引位置
*/
public static int buildTree(TreeNode[] t) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean check[] = new boolean[n];
for(int i = 0; i < n; i++) {
String index = sc.next();
String sl = sc.next();
String sr = sc.next();
TreeNode node = new TreeNode();
node.value = index;
if(sl.equals("-")) {
node.left = -1;
}else {
node.left = Integer.parseInt(sl);
check[node.left] = true;
}
if(sr.equals("-")) {
node.right = -1;
}else {
node.right = Integer.parseInt(sr);
check[node.right] = true;
}
t[i] = node;
}
int Root = 0;
for(int i = 0; i < check.length; i++) {
if(!check[i]) {
Root = i; break;
}
}
return Root;
}
/**
* 判断是否同构
* @param tt1 t1当前的索引位置
* @param tt2 t2当前的索引位置
* @param t1
* @param t2
* @return
*/
public static boolean isomorphism(int tt1, int tt2, TreeNode[] t1, TreeNode[] t2) {
if(tt1 == -1 && tt2 == -1) //t1,t2的当前节点都为空
return true;
else if((tt1 == -1 && tt2 != -1) || (tt1 != -1 && tt2 == -1)) //t1,t2的当前一个为空,一个不为空
return false;
else if(t1[tt1].value != t2[tt2].value) //t1,t2的当前节点的值不相等
return false;
else if(t1[tt1].left == -1 && t2[tt2].left == -1) { //t1,t2的左子树同时为空
return isomorphism(t1[tt1].right, t2[tt2].right, t1, t2);
}else if((t1[tt1].left != -1 && t2[tt2].left != -1) && (t1[t1[tt1].left].value == t2[t2[tt2].left].value)) {
return isomorphism(t1[tt1].left, t2[tt2].left, t1, t2)&&
isomorphism(t1[tt1].right, t2[tt2].right, t1, t2);
}else {
return isomorphism(t1[tt1].left, t2[tt2].right, t1, t2)&&
isomorphism(t1[tt1].right, t2[tt2].left, t1, t2);
}
}
}
判断二叉树是否同构
最新推荐文章于 2022-07-13 18:12:29 发布