二叉搜索树模板题
#include <bits/stdc++.h>
using namespace std;
typedef struct Node
{
int v;
Node *lchild;
Node *rchild;
} Node, *Tree;
//存放遍历结果
vector<int> ori, pre, mirpre, post, mirpost;
Node *newNode(int x)
{
Node *node = (Node *)malloc(sizeof(Node));
node->v = x;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
//构造二叉搜索树
void create(Tree &tree, int x)
{
if (tree == NULL)
{
Node *node = newNode(x);
tree = node;
return;
}
if (x < tree->v)
{
create(tree->lchild, x);
}
else
{
create(tree->rchild, x);
}
}
//先序遍历
void preOrder(Tree tree)
{
if (tree == NULL)
return;
pre.push_back(tree->v);
preOrder(tree->lchild);
preOrder(tree->rchild);
}
//镜像先序遍历
void preMOrder(Tree tree)
{
if (tree == NULL)
return;
mirpre.push_back(tree->v);
preMOrder(tree->rchild);
preMOrder(tree->lchild);
}
//后序遍历
void postOrder(Tree tree)
{
if (tree == NULL)
return;
postOrder(tree->lchild);
postOrder(tree->rchild);
post.push_back(tree->v);
}
//后序镜像遍历
void postMOrder(Tree tree)
{
if (tree == NULL)
return;
postMOrder(tree->rchild);
postMOrder(tree->lchild);
mirpost.push_back(tree->v);
}
Tree tree;
void print(vector<int> V){
for(int i = 0; i < V.size();i++){
if(i!=0)printf(" ");
printf("%d",V[i]);
}
printf("\n");
}
int main(void)
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int x;
scanf("%d", &x);
ori.push_back(x);
create(tree, x);
}
preOrder(tree);
preMOrder(tree);
postOrder(tree);
postMOrder(tree);
if (ori == pre)
{
cout <<"YES" << endl;
print(post);
}
else if (ori == mirpre)
{
cout <<"YES" << endl;
print(mirpost);
}
else
{
printf("NO\n");
}
return 0;
}