**
04-树4 是否同一棵二叉搜索树
**
思路:先建一个“样板树”,随后让数据下至树内。若与样板树的结构一致,则为真。
#include <iostream>
#include <vector>
using namespace std;
struct Tree {
int val=0;
Tree* left=NULL;
Tree* right=NULL;
bool flag = 0;//flag标记有没有来到过这个节点
};
bool checkVal(Tree* root, int treeVal)
{
if (root->flag)
{
if (treeVal < root->val)
return checkVal(root->left, treeVal);
if (treeVal > root->val)
return checkVal(root->right, treeVal);
}
else
{
if (root->val == treeVal)
{
root->flag = 1;
return 1;
}
return 0;
}
}
void resetTreeFlag(Tree* root)
{//先序遍历重置树的所有节点上的flag值。
if (!root)
return;
root->flag = 0;
resetTreeFlag(root->left);
resetTreeFlag(root->right);
}
bool isSameTree(Tree* root, vector<int> treeVal)
{
resetTreeFlag(root);
for (auto& it : treeVal)
{
if (!checkVal(root, it))
return 0;//若有任何一个节点不符合原来的树就返回假
}
return 1;
}
Tree* addTreeNode(Tree* root, int val)
{
if (!root)
{
Tree* newTree = new Tree;
newTree->val = val;
return newTree;
}
if (val > root->val)
{
root->right = addTreeNode(root->right,val);
return root;
}
else if (val < root->val)
{
root->left = addTreeNode(root->left, val);
return root;
}
}
int main()
{
int N;
cin >> N;
int L;
while (N)
{
cin >> L;
Tree *iniRoot =NULL;
for (int i = 0; i < N; i++)
{
int val;
cin >> val;
iniRoot = addTreeNode(iniRoot, val);
}
for (int i = 0; i < L; i++)
{
vector<int> treeVal;
for (int i = 0; i < N; i++)
{
int val;
cin >> val;
treeVal.push_back(val);
}
if (isSameTree(iniRoot, treeVal))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
cin >> N;
}
}