判断二叉树是否同构

在这里插入图片描述

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);
		}
	}


}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值