试编写一个算法,判断给定的二叉树是否是二叉排序树
#include <iostream>
#include <queue>
typedef struct node{int data;struct node* left;struct node* right;
}node,*pnode;pnode buynode(int x)
{pnode tmp=(pnode) malloc(sizeof (node));tmp->data=x;tmp->left= nullptr,tmp->right= nullptr;return tmp;
}void build_tree(pnode &root,int data)
{if(root== nullptr) {root= buynode(data);return;}if(data<root->data)build_tree(root->left,data);if(data==root->data) return;if(data>root->data) build_tree(root->right,data);
}void print(pnode root)
{if(root== nullptr) return;std::queue<pnode> record;record.push(root);int size=record.size();while(!record.empty()){pnode head=record.front();printf("%3d",head->data);record.pop();if(head->left) record.push(head->left);if(head->right) record.push(head->right);if(--size==0) puts(""),size=record.size();}
}
bool judgebst(pnode root)
{if(root== nullptr||(root->left== nullptr&&root->right== nullptr)) return true;if(root->left&&root->right) return judgebst(root->left)&& judgebst(root->right)&&root->left->data<root->data &&root->data<root->right->data;if(!root->left)return judgebst(root->right)&&root->data<root->right->data;else return judgebst(root->left)&&root->data>root->left->data;
}
int main() {pnode r1= nullptr;//p295图7.8(a),这是一棵二叉排序树int a[]={45,24,12,37,28,40,55,53,60,70};for(int i=0;i<10;i++){build_tree(r1,a[i]);}print(r1);if(judgebst(r1)) printf("this is a binary sort tree\n");else printf("this is not a binary sort tree\n");pnode r2= buynode(5);//构造一棵不是二叉排序树的树r2->left= buynode(7);r2->right= buynode(3);print(r2);if(judgebst(r2)) printf("this is a binary sort tree\n");else printf("this is not a binary sort tree\n");return 0;
}