Description
试编写程序,判别给定的二叉树是否为二叉排序树。设此二叉树以二叉链表作存储结构,且树中结点的关键字均不同。
Input
按先序输入二叉树各结点(结点值大于0),其中-1表示取消建立子树结点。
Output
若该二叉树为二叉排序树,则输出yes;否则,输出no。
- Sample Input
12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1
- Sample Output
yes
#include<stdio.h> #include<stdlib.h> typedef struct binarytree { int m; struct binarytree *lc; struct binarytree *rc; }bt; int step; int a[100]; bt* creat() // 创建二叉树 { int m; bt *t; scanf("%d",&m); if(m == -1) t = NULL; else { t = (bt* )malloc(sizeof(bt)); t->m = m; t->lc = creat(); t->rc = creat(); } return t; } void travel(bt *t) //按中序遍历将数值存储到数组中 { if(t == NULL) return ; else { travel(t->lc); a[step++] = t->m; travel(t->rc); } } void output() //二叉排序树的中序遍历应是递增的,以此来判断 { int k; int flag = 0; k = a[0]; for(int i = 1;i < step;i++) { if(k > a[i]) { flag = 1; break; } else { k = a[i]; } } if(flag == 0) printf("yes\n"); else printf("no\n"); } int main() { step = 0; bt *pbt; pbt = creat(); travel(pbt); output(); return 0; }