#include <cmath>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using Tree = struct TreeNode *;
struct TreeNode
{
Tree Left, Right;
int value;
bool flag;
};
int getdigit(void)
{
int digit{0}, symbol{1};
bool isvoid = true;
while (1)
{
char ch = getchar();
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == EOF)
{
if (isvoid)
continue;
return digit * symbol;
}
isvoid = false;
if (ch == '-')
symbol = -1;
else
digit = digit * 10 + ch - '0';
}
}
Tree NewNode(int Value)
{
Tree T = static_cast<Tree>(malloc(sizeof(TreeNode)));
T->value = Value;
T->Left = T->Right = nullptr;
T->flag = false;
return T;
}
Tree MadeTree(Tree T, int value)
{
if (T == nullptr)
T = NewNode(value);
else
{
if (value > T->value)
T->Right = MadeTree(T->Right, value);
else
T->Left = MadeTree(T->Left, value);
}
return T;
}
Tree CleanTree(Tree T)
{
if (T != nullptr)
{
T->flag = false;
T->Right = CleanTree(T->Right);
T->Left = CleanTree(T->Left);
}
return T;
}
bool CheckTree(Tree T, int Value)
{
if (Value == T->value)
{
T->flag = true;
return false;
}
if (T->flag == false)
return true;
if (Value > T->value)
return CheckTree(T->Right, Value);
return CheckTree(T->Left, Value);
}
void FreeTree(Tree T)
{
if (T != nullptr)
{
FreeTree(T->Left);
FreeTree(T->Right);
free(T);
T = nullptr;
}
}
int main(int argc, char *argv[])
{
int N{0}, L{0};
while ((N = getdigit()) != 0)
{
L = getdigit();
Tree T = nullptr;
for (auto i = 1; i <= N; ++i)
T = MadeTree(T, getdigit());
while (L--)
{
bool isp{false};
for (auto i = 1; i <= N; ++i)
{
if (isp)
{
getdigit();
continue;
}
isp = CheckTree(T, getdigit());
}
if (isp)
printf("No\n");
else
printf("Yes\n");
T = CleanTree(T);
}
FreeTree(T);
}
return EXIT_SUCCESS;
}
每个测试里,链表建一颗初始二叉树,每个节点设下一个 flag ,用于之后的判别。
检查输入序列对应的二叉树是否与初始二叉树相同,只需要检测输入序列建树的顺序即可。在初始二叉树中寻找输入序列的每个值,每次找到后都标记该节点已经走过;当寻找值时经过了一个之前没标记过的节点时立即退出,说明该输入序列的建树顺序与初始二叉树不同!
每个输入序列检查完毕后不要忘记清空初始二叉树的标记。
最后把树的申请空间都释放(好习惯,没有也可以)。