一、具体要求
二、分析
值得注意的是,由于左子树只包含小于当前节点的数,结点的右子树只包含大于当前节点的数,所以,除了判断每个根节点root->left>data < root->data和root->data > root->right->data是否成立外(当root,root->left和root->right存在),还需要额外判断root->left的右子树中是否存在过大的数,如果root->left的右子树中存在大于等于root->data的数,那么这个输就不是二叉排序树。
如下图所示,3的右子树数值为5,大于整个树根节点的值4。
同理,如果root->right的左子树存在过小的数,即存在小于等于root->data的数,这个树也不是二叉排序树。
如下图所示,5的左子树结点数值为2,小于整个树根节点的值4。
三、采用严题集定义的代码
严题集上对于二叉树的定义为:
typedef struct BiTNode{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
算法:
bool ISBST(BiTree root)
//9-31 判断是否为二叉排序树
{
if(!root) return true;
bool judge1=true,judge2=true;
if(root->lchild)
{
if(root->lchild->data>=root->data) return false;
if(root->lchild->rchild)
{
BiTree temp=root->lchild->rchild;
while(temp)
{
if(temp->data>=root->data) return false;
temp=temp->rchild;
}
}
judge1=ISBST(root->lchild);
}
if(root->rchild)
{
if(root->data>=root->rchild->data) return false;
if(root->rchild->lchild)
{
BiTree temp=root->rchild->lchild;
while(temp)
{
if(temp->data<=root->data) return false;
temp=temp->lchild;
}
}
judge2=ISBST(root->rchild);
}
if(judge1==true&&judge2==true) return true;
else
return false;
四、采用LeetCode平台定义的代码
LeetCode平台对二叉树的定义:
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
算法:
bool isValidBST(struct TreeNode* root)
{
if(!root) return true;
bool judge1=true,judge2=true;
if(root->left)
{
if(root->left->val>=root->val) return false;
if(root->left->right)
{
struct TreeNode *temp=root->left->right;
while(temp)
{
if(temp->val>=root->val) return false;
temp=temp->right;
}
}
judge1=isValidBST(root->left);
}
if(root->right)
{
if(root->val>=root->right->val) return false;
if(root->right->left)
{
struct TreeNode *temp=root->right->left;
while(temp)
{
if(temp->val<=root->val) return false;
temp=temp->left;
}
}
judge2=isValidBST(root->right);
}
if(judge1==true&&judge2==true) return true;
else return false;
}
五、算法效率
算法效率还是很高的!