分析 :二叉搜索树的判断(BST),本题要求判断输入序列是不是二叉搜索树的前序或者是该二叉搜索树的镜像的前序,代码有点长,但易懂
#include <iostream>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <queue>
#include <math.h>
#include <stack>
#include <algorithm>
#include <map>
#include <set>
#define MAX 99999999
typedef long long ll;
using namespace std;
int n, m;
vector< int > pre;
struct node{
int data;
struct node* left;
struct node* right;
} ;
int f;
void posTraversal1 ( node* root)
{
if ( root == NULL ) return ;
posTraversal1 ( root- > left) ;
posTraversal1 ( root- > right) ;
if ( f == 0 ) {
cout<< root- > data;
f = 1 ;
}
else
cout<< " " << root- > data;
}
void posTraversal2 ( node* root)
{
if ( root == NULL ) return ;
posTraversal2 ( root- > right) ;
posTraversal2 ( root- > left) ;
if ( f == 0 ) {
cout<< root- > data;
f = 1 ;
}
else
cout<< " " << root- > data;
}
void inser ( node * & root, int x)
{
if ( root == NULL )
{
root = ( node* ) malloc ( sizeof ( node) ) ;
root- > data = x;
root- > left = NULL ;
root- > right = NULL ;
}
else if ( root- > data <= x)
inser ( root- > right, x) ;
else inser ( root- > left, x) ;
}
node* create ( )
{
node* root = NULL ;
for ( int i = 0 ; i< n; i++ )
inser ( root, pre[ i] ) ;
return root;
}
vector< int > test_pre1;
void judge1 ( node * root)
{
if ( root == NULL )
return ;
test_pre1. push_back ( root- > data) ;
judge1 ( root- > left) ;
judge1 ( root- > right) ;
}
void judge2 ( node * root)
{
if ( root == NULL )
return ;
test_pre1. push_back ( root- > data) ;
judge2 ( root- > right) ;
judge2 ( root- > left) ;
}
int main ( )
{
cin>> n;
for ( int i = 0 ; i< n; i++ ) {
int x;
cin>> x;
pre. push_back ( x) ;
}
node* root = create ( ) ;
judge1 ( root) ;
if ( test_pre1 == pre)
{
cout<< "YES\n" ;
posTraversal1 ( root) ;
}
else {
test_pre1. clear ( ) ;
judge2 ( root) ;
if ( test_pre1 == pre)
{
cout<< "YES\n" ;
posTraversal2 ( root) ;
}
else
cout<< "NO" ;
}
return 0 ;
}