判定给定二叉树是否为二叉排序树

描述试写一个判定给定二叉树是否为二叉排序树的程序,设此二叉树以二叉链表做存储结构,且结点的关键字均不同

 

输入

输入一个二叉树的先序序列,若某个节点没有左孩子(右孩子),则左孩子(右孩子)用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;
	
} 

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值