This question examines the concept and nature of binary search trees
First of all, we must first understand the concept and properties of the
binary search tree: Binary Search Tree (Binary Search Tree), (also: binary search tree, binary sort tree) it is either an empty tree , or has the following properties Binary tree:
If its left subtree is not empty, the value of all nodes on the left subtree is less than the value of its root node;
if its right subtree is not empty, then the value of all nodes on the right subtree The value is greater than the value of its root node;
its left and right subtrees are also binary sort trees.
As a classic data structure, the binary search tree has the characteristics of fast insertion and deletion operations of linked lists, and the advantage of fast search of arrays; therefore, it is widely used, such as file systems and database systems. The data structure performs efficient sorting and retrieval operations.
//创建二叉树
BinTree BuildTree()/* 由裁判实现,细节不表 */
{
int n;
BinTree p = (BinTree)malloc(sizeof(struct TNode));
if(p==NULL) return NULL;
scanf("%d",&n);
getchar();
if(n==-1) return NULL;//判断是否为叶结点
else
{
p->Data = n;
printf("请输入 %d 的左子结点: ",n );
p->Left=BuildTree();
printf("请输入 %d 的右子结点: ",n );
p->Right=BuildTree();
}
return p;
}
//AC代码
//由二叉搜索树的性质得出:按中序遍历二叉排序树所得到中序序列是一个递增有序序列
//思路:获取中序遍历序列,再判断该序列是否递增有序,就能得出此二叉树是否为二叉搜索树
bool IsBST ( BinTree T )
{
BinTree *b[100];
int a[100];
int i=0;
int j;
int count=0;
BinTree p=T;
int top = -1;
if(T==NULL) return true; /*空树也是二叉排序(搜索)树*/
while(p!=NULL||top!=-1) /*非递归(栈+循环)中序遍历*/
{
if(p!=NULL)
{
b[++top] = p;
p = p->Left;
}
else
{
p = b[top--];
a[i++] = p->Data;
p = p->Right;
}
}
for(j = 0 ; j<i ; ++j) /*判断该数组是否是递增的有序系列*/
{
if(a[j]<=a[j+1]&&j+1<i) count++;
}
if(count==i-1) return true;
else return false;
}
Today, I went to the blog to see the code of a great god, well written, and attached a link:
whether binary search tree