题目:http://pat.zju.edu.cn/contests/pat-a-practise/1043
//递归 先序遍历 后序遍历 先序构造二叉查找树,之后后序遍历
//思路和代码请参考
http://linest.github.io/blog/2013/06/16/pat_1043/ ,这位大神写的很好。
参考代码:
#include<cstdio>
#include<vector>
using namespace std;
struct NODE
{
int value;
NODE *left, *right;
NODE():left(NULL),right(NULL){};
NODE(int v):left(NULL),right(NULL),value(v){};
};
void insert(NODE* &root, int v)
{
if(root == NULL)
{
root = new NODE(v);
}
else
{
if(v < root->value)
{
insert(root->left, v);
}
else
{
insert(root->right, v);
}
}
}
void pre_order_traversal(NODE* &root, vector<int>& vec)
{
if(root != NULL)
{
vec.push_back(root->value);
}
if(root->left)
{
pre_order_traversal(root->left, vec);
}
if(root->right)
{
pre_order_traversal(root->right, vec);
}
}
void pre_order_traversal_mirror(NODE* &root, vector<int>& vec)
{
if(root != NULL)
{
vec.push_back(root->value);
}
if(root->right)
{
pre_order_traversal_mirror(root->right, vec);
}
if(root->left)
{
pre_order_traversal_mirror(root->left, vec);
}
}
int post_pos = 0;
void post_order_traversal(NODE* &root)
{
if(root->left)
post_order_traversal(root->left);
if(root->right)
post_order_traversal(root->right);
post_pos++ == 0 ? printf("%d", root->value) : printf(" %d", root->value);
}
int post_mirror_pos = 0;
void post_order_traversal_mirror(NODE* &root)
{
if(root->right)
post_order_traversal_mirror(root->right);
if(root->left)
post_order_traversal_mirror(root->left);
post_mirror_pos++ == 0 ? printf("%d", root->value) : printf(" %d", root->value);
}
int main()
{
int N, arr[1001];
NODE* root = NULL;
bool flag = true;
vector<int> pre_vec, post_vec;
scanf("%d", &N);
for(int i = 0; i<N; ++i)
{
scanf("%d", arr+i);
insert(root, arr[i]);
}
pre_order_traversal(root, pre_vec);
for(int i = 0; i<N; ++i)
{
if(pre_vec.at(i) != arr[i])
{
flag = false;
break;
}
}
if(flag)
{
printf("YES\n");
post_order_traversal(root);
}
else
{
flag = true;
pre_order_traversal_mirror(root, post_vec);
for(int i = 0; i<N; ++i)
{
if(post_vec.at(i) != arr[i])
{
flag = false;
break;
}
}
if(flag)
{
printf("YES\n");
post_order_traversal_mirror(root);
}
else
{
printf("NO\n");
}
}
return 0;
}