Contest100000613 - 《算法笔记》9.4小节——数据结构专题(2)->二叉查找树(BST)

题目链接

A 二叉排序树

  1. 建立 BST,然后先序遍历,中序遍历,后续遍历,简单题。
  2. 注意可能有重复元素,重复元素无需添加到 BST 中。参考代码如下。
#include<iostream>

using namespace std;

struct node {
	int data;
	node* left = NULL;
	node* right = NULL;
};
void insert(node* &root, int data) {
	if (root == NULL) {
		root = new node;
		root->data = data;
	}
	else if (root->data < data)
		insert(root->right, data);
	else if (root->data > data)
		insert(root->left, data);
	else return;
}
void pre(node* root) {
	if (root == NULL) return;
	cout << root->data << ' ';
	pre(root->left);
	pre(root->right);
}
void in(node* root) {
	if (root == NULL) return;
	in(root->left);
	cout << root->data << ' ';
	in(root->right);
}
void post(node* root) {
	if (root == NULL) return;
	post(root->left);
	post(root->right);
	cout << root->data << ' ';
}

int main() {
	int n, data;
	while (cin >> n) {
		node* BST = NULL;
		for (int i = 0; i < n; i++) {
			cin >> data;
			insert(BST, data);
		}
		pre(BST);
		cout << endl;
		in(BST);
		cout << endl;
		post(BST);
		cout << endl;
	}
	return 0;
}

B 二叉搜索树

  1. 建立两个二叉搜索树,然后比较两棵二叉树是否相同。
  2. 因为先序序列和中序序列可以唯一确定一棵二叉树,故判断两棵二叉树是否相同可以比较它们的先序序列和中序序列是否分别相同。参考代码如下。
#include<iostream>
#include<string>
#include<vector>

using namespace std;

struct node {
	char data;
	node* left = NULL;
	node* right = NULL;
};

void build(node* &root,char data) {
	if (root == NULL) {
		root = new node;
		root->data = data;
	}
	else if (root->data < data)
		build(root->right, data);
	else build(root->left, data);
}

void pre(node* root, vector <char> &v) {
	if (root == NULL) return;
	v.push_back(root->data);
	pre(root->left, v);
	pre(root->right, v);
}

void in(node* root, vector <char> &v) {
	if (root == NULL) return;
	in(root->left, v);
	v.push_back(root->data);
	in(root->right, v);
}

bool cmp(node* BST1, node* BST2) {
	vector <char> pre1, pre2;
	vector <char> in1, in2;
	pre(BST1, pre1); pre(BST2, pre2);
	in(BST1, in1); in(BST2, in2);
	if (pre1 == pre2 && in1 == in2) return true;
	else return false;
}

int main() {
	int n;
	string s;
	while (cin >> n && n) {
		cin >> s;
		node* BST = NULL;
		for (int i = 0; i < s.size(); i++)
			build(BST, s[i]);
		for (int i = 0; i < n; i++) {
			cin >> s;
			node* temp_BST = NULL;
			for (int i = 0; i < s.size(); i++)
				build(temp_BST, s[i]);
			if (cmp(BST, temp_BST))
				cout << "YES" << endl;
			else cout << "NO" << endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42717165/article/details/87622216
今日推荐