#include<iostream>
using namespace std;
struct Node
{
int data;
Node* left;
Node* right;
};
bool IsSubtreeLesser(Node* root, int value)
{
if(root == NULL) return true;
if(root->data <= value && IsSubtreeLesser(root->left, value)
&& IsSubtreeLesser(root->left, value))
return true;
else
return false;
}
bool IsSubtreeGreater(Node* root, int value)
{
if(root == NULL) return true;
if(root->data > value && IsSubtreeGreater(root->left, value)
&& IsSubtreeGreater(root->left, value))
return true;
else
return false;
}
bool IsBinarySearchTree(Node* root)
{
if(root == NULL) return true;
if(IsSubtreeLesser(root->left,root->data)
&& IsSubtreeGreater(root->right,root->data)
&& IsBinarySearchTree(root->left)
&& IsBinarySearchTree(root->right))
return true;
else return false;
}
Node* GetNewNode(int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
Node* Insert(Node* root, int data)
{
if(root == NULL)//数是空的
{
root = GetNewNode(data);
return root;
}
else if(data <= root->data)
root->left = Insert(root->left,data);
else root->right = Insert(root->right,data);
return root;
}
int main()
{
Node* root = NULL;//表示树是空的
root = Insert(root,15);
root = Insert(root,10);
root = Insert(root,20);
root = Insert(root,25);
root = Insert(root,8);
root = Insert(root,12);
if(IsBinarySearchTree(root)) printf("该二叉树是二叉搜索树\n");
else printf("该二叉树不是二叉搜索树\n");
return 0;
}
判断是否是二叉搜索树
最新推荐文章于 2024-07-14 13:39:50 发布