PAT whether Structures and Algorithms 7-4 with a binary search tree (40 rows streamlined structure)

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/99694043

Are 7-4 with a binary search tree (25 points)

Given a sequence of insertion can be uniquely determined a binary search tree. However, given a binary search tree, but can be obtained from a variety of different insert sequence. 2, respectively, according to a sequence {e.g., 1, 3} and {2, 3, 1} is inserted into an initially empty binary search tree, the same results were obtained. Thus the insertion sequence for the various input, you need to determine whether they are able to generate the same binary search tree.

Input formats:

Comprising a plurality of groups of test data input. Each row of the first data is given two positive integers N (≤10) and L, respectively, and the need to check the number of the number sequence of each insertion sequence element. Line 2 shows a space-separated positive integer number N, as the initial insertion sequence. Finally L rows, each row gives N insertion element belonging to the L sequence needs to be checked.

For simplicity, we ensure that each insert is a sequence of 1 to N arranged. When N is 0 to read, it marks the end of the input, this set of data not processed.

Output formats:

If it generates a binary search tree with the corresponding initial sequence generated by the same sequence each group needs to be checked, output "Yes", otherwise a "No".

Sample input:

4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

Sample output:

Yes
No
No

 

#include<iostream>
#include <map>
using namespace std;
struct Node{
	int left, right;
};
struct Tree {
	map<int, Node> tree;
	int root = 0;
	Tree(int n) {
		int tmp;
		for (int i = 0; i < n; ++i) {
			cin >> tmp;
			insert(tmp);
		}
	}
	void insert(int& t) {
		int* k = &root;
		while (*k!=0) 
			k = (t < *k ? &tree[*k].left : &tree[*k].right);
		*k = t;
	}
	bool operator ==(Tree& other) {
		if (tree.size() != other.tree.size() || root != other.root)
			return false;
		for (auto& it : other.tree) {
			if(it.second.left!=tree[it.first].left|| it.second.right != tree[it.first].right)
				return false;
		}
		return true;;
	}
};
int main(){
	int n, l;
	while (cin >> n >> l) {
		Tree refer(n);
		for (int i = 0; i < l; ++i) {
			Tree cTree(n);
			cout << (cTree == refer ? "Yes" : "No") << endl;
		}
	}
	return 0;
}

 

Guess you like

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