描述试写一个判定给定二叉树是否为二叉排序树的程序,设此二叉树以二叉链表做存储结构,且结点的关键字均不同
输入
输入一个二叉树的先序序列,若某个节点没有左孩子(右孩子),则左孩子(右孩子)用0表示
输出
输出二叉树的中序遍历序列,并判断该二叉树是否为二叉排序树,若是,则输出“It is an BinaryOrderTree!”,否则输出“It is not an BinaryOrderTree!”
输入样例
5 3 2 0 0 4 0 0 7 6 0 0 8 0 0
输出样例
2
3
4
5
6
7
8
It is an BinaryOrderTree!
提示
中序遍历二叉排序树可以得到一个关键字的升序序列,可以此作为判定依据
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
typedef struct node{
int info;
node* lchild;
node* rchild;
}node,*Pnode;
Pnode creat(){//先序创建二叉树
Pnode p;
int num;
cin>>num;
if(num==0) p=NULL;
else{
p=(Pnode)malloc(sizeof(node));
p->info=num;
p->lchild=creat();
p->rchild=creat();
}
return p;
}
void output(Pnode t){//中序输出二叉树
if(t){
output(t->lchild);
cout<<t->info<<endl;
output(t->rchild);
}
}
int isBinaryTree(Pnode t){//判断是否二叉排序树
if(t){
if(t->lchild==NULL&&t->rchild==NULL) return 1; //左右孩子均为空,返回1
else if(t->lchild==NULL) {
if(t->info<t->rchild->info) return isBinaryTree(t->rchild);
else return 0;
}//左孩子为空,判断右孩子
else if(t->rchild==NULL) {
if(t->info>t->lchild->info) return isBinaryTree(t->lchild);
else return 0;
}//有孩子为空,判断左孩子
else{
if(t->info>t->lchild->info&&t->info<t->rchild->info)
return isBinaryTree(t->rchild)&&isBinaryTree(t->lchild);
else return 0;
}//左右孩子均有
}
}
int main(){
Pnode p=creat();
output(p);
if(isBinaryTree(p)) cout<<"It is an BinaryOrderTree!"<<endl;
else cout<<"It is not an BinaryOrderTree!"<<endl;
}