- 二叉排序树的判断
- 1.判断条件:左 < 中 < 右
- 2.递归判断左右子树
- 3.递归结束条件:该结点为叶子结点
- 建树方式(先序)
- 列子:AB#D##C##
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include <iostream>
#define MAXSIZE 10010
#define ElemType int
using namespace std;
typedef struct BTNode{
ElemType data;
BTNode *lchild,*rchild;
}*BTree;
BTree CreateTree(){
ElemType ch;
printf("输入结点元素值:");
scanf("%d",&ch);
if(ch == 0)
return NULL;
else{
BTree tree=(BTree)malloc(sizeof(BTree));
tree->data=ch;
printf("%d 结点左子树\n",ch);
tree->lchild=CreateTree();
printf("%d 结点右子树\n",ch);
tree->rchild=CreateTree();
return tree;
}
}
void LayeredOrderTravel(BTree tree){
queue<BTree> queue1;
BTree p;
if(tree){
queue1.push(tree);
while(!queue1.empty()){
p=queue1.front();
queue1.pop();
printf("%d ",p->data);
if(p->lchild)
queue1.push(p->lchild);
if(p->rchild)
queue1.push(p->rchild);
}
}
}
bool IsSortBinaryTree(BTree tree){
printf("%d\n",tree->data);
if(!tree)
return true;
BTree lChildD=tree->lchild;
BTree rChildD=tree->rchild;
if( (lChildD && (lChildD->data > tree->data) ) || (rChildD && (rChildD->data < tree->data) ) ){
return false;
}
else if(!lChildD || !rChildD){
return true;
}
else{
return IsSortBinaryTree(tree->lchild)&&IsSortBinaryTree(tree->rchild);
}
}
int main(){
printf("二叉树的建立\n");
BTree tree;
tree=CreateTree();
printf("二叉树的层序遍历\n");
LayeredOrderTravel(tree);
printf("\n判断是否为二叉排序树\n");
bool flag=true;
flag=IsSortBinaryTree(tree);
if(flag)
printf("该树是二叉排序树\n");
else
printf("该树不是二叉排序树\n");
return 0;
}
}
}