二叉搜索树
题目描述
判断两序列是否为同一个二叉搜索树序列。
输入描述
第一行是一个数 n ( 1 <= n <= 20 ),表示有 n 个二叉搜索树序列需要判断。
接下去一行是一个序列,序列长度小于 10 ,包含 0 ~ 9 的数字,没有重复数字,根据这个序列可以构造出一棵二叉搜索树。
接下去的 n 行有 n 个序列,每个序列格式跟第一个序列一样,请判断这两个序列——该行序列和第二行序列是否能组成同一棵二叉搜索树。
输出描述
对于最后 n 行的每一行询问,如果序列相同则输出 YES,否则输出 NO。
用例输入 1
2
567432
543267
576342
用例输出 1
YES
NO
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node // 节点
{
int val;
node *lc, *rc;
};
bool ok; // 当前询问中两树是否相同
node *insert(node *p, int x) // 中序序列构建二叉搜索树
{
if (p == NULL) // 当前节点为空
{
// 创建新节点
node *new_node = new node;
new_node->val = x;
new_node->lc = NULL;
new_node->rc = NULL;
return new_node;
}
else // 当前节点不为空
{
// 二叉搜索树的遍历过程,从而找到应该建立新节点的位置
if (p->val > x)
p->lc = insert(p->lc, x);
else
p->rc = insert(p->rc, x);
return p;
}
}
void check(node *standard_root, node *root)
{
if (standard_root != NULL && root != NULL) // 两棵树该节点都不为空
{
// 中序遍历
check(standard_root->lc, root->lc);
if (standard_root->val != root->val) // 判断对应节点值是否相同
{
ok = false;
return; // 若已确定答案,无需继续递归
}
check(standard_root->rc, root->rc);
}
else if (standard_root != NULL || root != NULL) // 一棵树有该节点,另一棵树没有对应节点,说明两树不相同
{
ok = false;
return; // 若已确定答案,无需继续递归
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
string s;
cin >> n;
node *standard_root = NULL;
cin >> s;
for (int i = 0; i < s.size(); i++) // 构建标准树
standard_root = insert(standard_root, s[i] - '0');
for (int i = 0; i < n; i++) // n个二叉搜索树,对应n个询问
{
ok = true; // 每次询问都要先初始化为true
node *root = NULL;
cin >> s;
for (int i = 0; i < s.size(); i++) // 构建询问树
root = insert(root, s[i] - '0');
check(standard_root, root); // 中序遍历,判断两棵树是否一致
if (ok)
cout << "YES" << '\n';
else
cout << "NO" << '\n';
}
return 0;
}