PTA数据结构与算法题目集(中文)7-3 树的同构 (25 分)

#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1

class TreeNode {

	public:
	
		ElementType element;
		Tree left;
		Tree right;

};

TreeNode t1[MaxTree], t2[MaxTree];

Tree BuildTree(TreeNode t[]);
int isomorphic(Tree root1, Tree root2);

using namespace std;

int main()
{
	Tree root1, root2;
	char *temp;

	root1 = BuildTree(t1);
	root2 = BuildTree(t2);

	if (isomorphic(root1, root2)) {
		cout << "Yes" << endl;
	}
	else {
		cout << "No" << endl;
	}
	gets(temp); 
	return 0;
	system("pause");
}

Tree BuildTree(TreeNode t[])
{
	Tree root = -1;
	char temp_left, temp_right;
	int N, i;
	cin >> N;

	if (N) {

		int check[MaxTree];

		for (i = 0; i < N; i++) {

			check[i] = 0;

		}

		for (i = 0; i < N; i++) {

			cin >> t[i].element >> temp_left >> temp_right;

			if (temp_left != '-') {

				t[i].left = temp_left - '0';
				check[t[i].left] = 1;

			}
			else {

				t[i].left = Null;

			}

			if (temp_right != '-') {

				t[i].right = temp_right - '0';
				check[t[i].right] = 1;

			}
			else {

				t[i].right = Null;

			}
		}

		for (i = 0; i < N; i++) {

			if (!check[i]) break;

		}

		root = i;

		return root;
	}
	else return Null;

}

int isomorphic(Tree root1, Tree root2)
{
	if ((root1 == Null) && (root2 == Null)) return 1;
	if (((root1 == Null) && (root2 != Null)) || ((root1 != Null) && (root2 == Null))) return 0;
	if (t1[root1].element != t2[root2].element) return 0;
	if ((t1[root1].left == Null) && (t2[root2].left == Null)) return isomorphic(t1[root1].right, t2[root2].right);
	if ((t1[root1].left != Null) && (t2[root2].left != Null) && (t1[t1[root1].left].element == t2[t2[root2].left].element)) {

		return (isomorphic(t1[root1].left, t2[root2].left) && isomorphic(t1[root1].right, t2[root2].right));

	}
	else {

		return (isomorphic(t1[root1].left, t2[root2].right) && isomorphic(t1[root1].right, t2[root2].left));

	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值