题目详情:https://www.patest.cn/contests/pat-a-practise/1043
提交:
提交代码:
#include <iostream>
#include <malloc.h>
#include <vector>
using namespace std;
#define N 1010
typedef struct BTree
{
int data;
struct BTree* leftChild;
struct BTree* rightChild;
}BTree;
vector<int> post,postMirror;
int number[N],n;
int numberT[N],rear;
BTree* insertBST( BTree *root,int key ) //插入一个节点到二叉排序树
{
if( root == NULL )
{
root = (BTree*)malloc(sizeof(BTree));
root->data = key;
root->leftChild = root->rightChild = NULL;
}
else if( root->data > key ) //根节点中的值大,则到左子树中去
{
root->leftChild = insertBST(root->leftChild,key);
}
else if( root->data <= key )
{
root->rightChild = insertBST(root->rightChild,key);
}
return root;
}
void preOrder( BTree *bt ) //对二叉排序树进行先序遍历
{
if( bt != NULL )
{
numberT[++rear] = bt->data;
preOrder(bt->leftChild);
preOrder(bt->rightChild);
}
}
void preOrderMirror( BTree *bt )//对镜像树进行先序遍历
{
if( bt != NULL )
{
numberT[++rear] = bt->data;
preOrderMirror( bt->rightChild );
preOrderMirror( bt->leftChild );
}
}
void postOrder( BTree *bt )//对二叉排序树进行后续遍历
{
if( bt != NULL )
{
postOrder(bt->leftChild);
postOrder(bt->rightChild);
post.push_back(bt->data);
}
}
void postOrderMirror( BTree *bt ) //对镜像树进行后序遍历
{
if( bt != NULL )
{
postOrderMirror( bt->rightChild );
postOrderMirror( bt->leftChild );
postMirror.push_back(bt->data);
}
}
bool compareArray( int array1[],int array2[] ) //比较两个数组是否相等
{
for( int i=0;i<n;++i )
{
if( array1[i] != array2[i] )
return false;
}
return true;
}
int main()
{
cin>>n;
BTree* root = NULL;
for( int i=0;i<n;++i )
{
cin>>number[i];
root = insertBST(root,number[i]);
}
rear = -1;
preOrder(root);
bool result1 = compareArray(number,numberT);
if( result1 )
{ //是二叉排序树
cout<<"YES"<<endl;
postOrder(root);
for( int i=0;i<post.size();++i )
{
if( i == post.size()-1 )
cout<<post[i]<<endl;
else
cout<<post[i]<<" ";
}
return 0;
}
//如果不是,则检查是否为镜像树
rear = -1;
preOrderMirror(root);
bool result2 = compareArray(number,numberT);
if( result2 )
{
cout<<"YES"<<endl;
postOrderMirror(root);
for( int i=0;i<postMirror.size();++i )
{
if( i == postMirror.size()-1 )
cout<<postMirror[i]<<endl;
else
cout<<postMirror[i]<<" ";
}
return 0;
}
else
cout<<"NO"<<endl;
return 0;
}
不要问我为什么可以对镜像树的先序遍历,后序遍历可以写成这样,我也是看的别人说的算法思想,然后自己写出来的,具体的我也不太懂。