7-28 搜索树判断
题目链接
关键点:
1、建二叉树,根据输入的先序遍历直接插入,如果为根节点,那么创建空间,初始化左右子树,如果不为,那么就将当前datax和当前结点的data比较,大于则插入左子树,小于插入右子树
2、建好树,之后开始先序遍历该二叉树,比较和当前给出数组是否相同,如果不通,就比较和镜像的先序是否相同
3、镜像先序:则将先序的跟左右,改为跟右左
镜像后序:将后序的左右跟,改为右左根
完整代码:
# include <iostream>
# include <algorithm>
# include <vector>
using namespace std;
vector<int> v1, v2, v3, v4;
int N;
int A[1010];
typedef struct TNode *PtrTree;
struct TNode{
int data;
PtrTree Left;
PtrTree Right;
};
PtrTree Insert(PtrTree root, int x)
{
if (root == NULL)
{
root = (PtrTree)malloc(sizeof(struct TNode));
root->data = x;
root->Left = NULL;
root->Right = NULL;
return root;
}
if (root->data > x)
root->Left = Insert(root->Left, x);
else if (root->data <= x)
root->Right = Insert(root->Right, x);
else
return NULL;
return root;
}
PtrTree CreateTree(PtrTree root, int A[])
{
root = NULL;
for (int i=0; i<N; i++)
{
root = Insert(root, A[i]);
}
return root;
}
void Pre1(PtrTree root)
{
if (root!=NULL)
{
int temp = root->data;
v1.push_back(temp);
Pre1(root->Left);
Pre1(root->Right);
}
}
void Pro1(PtrTree root)
{
if (root != NULL)
{
Pro1(root->Left);
Pro1(root->Right);
int temp = root->data;
v2.push_back(temp);
}
}
void Pre2(PtrTree root)
{
if (root!=NULL)
{
int temp = root->data;
v3.push_back(temp);
Pre2(root->Right);
Pre2(root->Left);
}
}
void Pro2(PtrTree root)
{
if (root != NULL)
{
Pro2(root->Right);
Pro2(root->Left);
int temp = root->data;
v4.push_back(temp);
}
}
int judgement(int A[], vector<int>&v)
{
for (int i=0; i<N; i++)
{
if (A[i]!=v[i])
return 0;
}
return 1;
}
int main()
{
cin>>N;
for (int i=0; i<N; i++)
cin>>A[i];
PtrTree root;
root = CreateTree(root, A);
Pre1(root);
int flag1 = judgement(A, v1);
if (flag1 == 1)
{
cout<<"YES"<<endl;
Pro1(root);
for (int i=0; i<N; i++)
{
if (i<N-1)
cout<<v2[i]<<" ";
else
cout<<v2[i];
}
}
else
{
Pre2(root);
int flag2 = judgement(A, v3);
if (flag2 == 1)
{
cout<<"YES"<<endl;
Pro2(root);
for (int i=0; i<N; i++)
{
if (i<N-1)
cout<<v4[i]<<" ";
else
cout<<v4[i];
}
}
else
cout<<"NO"<<endl;
}
return 0;
}