一、思路
step1:建树
typedef struct node
{
int data;
struct node *lchild, *rchild;
}node;
node *root = NULL;
void create( node *&T, int key )
{
if( !T )
{
T = (node*)malloc(sizeof(node));
T->data = key;
T->lchild = T->rchild = NULL;
}
else if( key < T->data )
create(T->lchild, key);
else create(T->rchild, key);
}
step2:比较是否为先序序列,若不是则交换所有结点左右子树再比较
bool preorder( node *&t, int tag, node *root )
{
if( !t )
return true;
if( t == root )
index = 0;
if( t->data != pre[index++] )
return false;
if( tag )
swap(t->lchild, t->rchild);
return ( preorder(t->lchild, tag, root) && preorder(t->rchild, tag, root) );
}
step3:输出
void postorder( node *T )
{
if( T )
{
postorder(T->lchild);
postorder(T->rchild);
printf("%s%d", index++ ? " ":"", T->data);
}
}
二、代码
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct node
{
int data;
struct node *lchild, *rchild;
};
int index = 0;
vector<int> pre(1000);
void create( node *&t, int key )
{
if( !t )
{
t = new node;
t->data = key;
t->lchild = t->rchild = NULL;
}
else if( key < t->data )
create(t->lchild, key);
else create(t->rchild, key);
}
bool preorder( node *&t, int tag, node *root )
{
if( !t )
return true;
if( t == root )
index = 0;
if( t->data != pre[index++] )
return false;
if( tag )
swap(t->lchild, t->rchild);
return ( preorder(t->lchild, tag, root) && preorder(t->rchild, tag, root) );
}
void postorder( node *t, node *root )
{
if( t )
{
postorder(t->lchild, root);
postorder(t->rchild, root);
printf("%d%s", t->data , t == root ? "":" ");
}
}
int main()
{
int N;
node *root = NULL;
scanf("%d", &N);
for( int i = 0; i < N; ++i )
{
scanf("%d", &pre[i]);
create(root, pre[i]);
}
if( preorder(root, 0, root) || preorder(root, 1, root) )
{
printf("YES\n");
postorder(root, root);
}
else printf("NO");
}