PAT and homogeneous structure tree algorithm 7-3 (Compact line 30)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_40946921/article/details/99693140

7-3 homogeneous tree (25 minutes)

Given two trees T1 and T2. If T1 can be interchanged by several times about the child becomes T2, the two trees we call a "homogeneous" is. For example, Figure 1 shows two trees is isomorphic, as we have a tree in which the nodes A, B, G around the child interchange, get another tree. And FIG. 2 is not homogeneous.

 

 

figure 1

figure 2

Now given the two trees, you determine whether they are isomorphic.

 

Input formats:

2 input information given binary tree. For each tree, the first row is given a non-negative integer N (≦ 10), i.e., the number of nodes in the tree (assuming this case from node number 0 to N-1); followed by N rows, corresponding to the i-th row No. i-th node, the given node is stored in a capital letters, its left child node number, right child node numbers. If the child node is empty, then given the corresponding position "-." Separated by a space between the data given. Note: Title ensure that each node is stored in a different letter.

Output formats:

If two trees are isomorphic, output "Yes", otherwise a "No".

Input Sample 1 (corresponding to FIG. 1):

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 -

Output Sample 1:

Yes

Input Sample 2 (corresponding to FIG. 2):

8
B 5 7
F - -
A 0 3
C 6 -
H - -
D - -
G 4 -
E 1 -
8
D 6 -
B 5 -
E - -
H - -
C 0 2
G - 3
F - -
A 1 4

Output Sample 2:

No

 

#include<iostream>
#include <vector>
#include<string>
#include <map>
using namespace std;
struct Node{
	char* left,* right;
	char l, r;
};
void input(map<char, Node>& tree) {
	int n;
	string a, b;
	cin >> n;
	vector<char> nodes(n);
	for (int i = 0; i < n; ++i) {
		cin >> nodes[i] >> a >> b;
		tree[nodes[i]] ={ a == "-" ? nullptr : &nodes[stoi(a)] ,b == "-" ? nullptr : &nodes[stoi(b)] };
	}
	for (auto& it : tree)		//不能用指针做为参考,指针出函数就无效
		it.second.l = it.second.left!=nullptr?*it.second.left:'-', it.second.r = it.second.right!= nullptr ? *it.second.right: '-';
}
bool judge(map<char, Node>& a, map<char, Node>& b) {
	if (a.size() != b.size())
		return false;
	for (auto& it : a) {
		if (it.second.l != b[it.first].r && it.second.r != b[it.first].l&&		//互换
			(it.second.l != b[it.first].l && it.second.r != b[it.first].r))		//不互换
			return false;
	}
	return true;
}
int main(){
	map<char, Node> a, b;
	input(a); input(b);
	cout << (judge(a, b)?"Yes":"No");
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_40946921/article/details/99693140