利用本题, 复习二叉搜索树的创建(插入),先序遍历和后序遍历,以及掌握BST的特性
以下来自《算法笔记》对二叉查找树的介绍
二叉查找树(Binary Search Tree, BST)是一种特殊的二叉树,又称排序二叉树、二叉搜索树、二叉排序树。二叉查找树的递归定义如下:
1.要么二叉查找树是一棵空树
2.要么二叉查找树由根节点、左子树、右子树组成,其中左子树和右子树都是二叉树查找树,且左子树上所有结点的数据域均小于或等于根节点的数据域,右子树上所有结点的数据域均大于根节点的数据域。从二叉查找树的定义中可以知道,二叉查找树实际上是一棵数据域有序的二叉树。
二叉查找树一个实用的性质:对二叉查找树进行中序遍历,遍历的结果是有序的。
注意:定义根结点时要将其设为空节点(一开始是没有元素的);在新建结点时要注意将其左右子结点地址设为NULL
#include <cstdio>
#include <cstring>
const int maxn=1e3+1;
int n, a[maxn], b[maxn], c[maxn];
int cnt=0;
struct node{
int data;
node* lchild;
node* rchild;
};
node* newnode(int x){
node* temp=new node;
temp->data=x;
temp->lchild=NULL;
temp->rchild=NULL;
return temp;
}
void insert(node* &root, int x){ //插入
if(root==NULL){
root=newnode(x);
return;
}
if(root->data>x)
insert(root->lchild, x);
else
insert(root->rchild, x);
}
node* Create(){ //创建
node* root=NULL; //pay attention please!!!;
for(int i=0; i<n; i++)
insert(root, a[i]);
return root;
}
void traversal1(node* root){
if(cnt==n)
return;
if(root==NULL)
return;
b[cnt++]=root->data;
traversal1(root->lchild);
traversal1(root->rchild);
}
void traversal2(node* root){
if(cnt==n)
return;
if(root==NULL)
return;
b[cnt++]=root->data;
traversal2(root->rchild);
traversal2(root->lchild);
}
void postorder1(node* root){ //后序遍历——先左后右,最后根
if(root==NULL)
return;
postorder1(root->lchild);
postorder1(root->rchild);
c[cnt++]=root->data;
}
void postorder2(node* root){ //后序遍历——先左后右,最后根
if(root==NULL)
return;
postorder2(root->rchild);
postorder2(root->lchild);
c[cnt++]=root->data;
}
int main()
{
scanf("%d", &n);
for(int i=0; i<n; i++)
scanf("%d", &a[i]);
node* root=Create();
bool f1=true, f2=true;
cnt=0;
traversal1(root);
for(int i=0; i<n; i++){
if(a[i]!=b[i]){
f1=false;
break;
}
}
cnt=0;
traversal2(root);
for(int i=0; i<n; i++){
if(a[i]!=b[i]){
f2=false;
break;
}
}
cnt=0;
if(f1 || f2){
printf("YES\n");
if(f1)
postorder1(root);
if(f2)
postorder2(root);
for(int i=0; i<n; i++){
printf("%d", c[i]);
if(i!=n-1)
printf(" ");
else
printf("\n");
}
} else
printf("NO\n");
return 0;
}