
二叉树是一种树形数据结构,每个节点都有两个子节点。这两个子节点被称为左子节点和右子节点。
二叉搜索树(BST)是一种树形结构,其中左子树包含小于根节点的值的节点,右子树包含大于根节点的值的节点。
在这里,我们将检查一个二叉树是否是BST:
为了检查这个,我们需要在二叉树上检查BST条件。对于根节点,左子节点的值应该小于根节点的值,右子节点的值应该大于根节点的值,对于树中所有存在子节点的节点都要满足这个条件。
立即学习“C语言免费学习笔记(深入)”;
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
class node {
public:
int data;
node* left;
node* right;
node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
int isBSTUtil(node* node, int min, int max);
int isBST(node* node) {
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
int isBSTUtil(node* node, int min, int max) {
if (node==NULL)
return 1;
if (node->data < min || node->data > max)
return 0;
return
isBSTUtil(node->left, min, node->data-1) && isBSTUtil(node->right, node->data+1, max);
}
int main() {
node *root = new node(8);
root->left = new node(3);
root->right = new node(10);
root->left->left = new node(1);
root->left->right = new node(6);
if(isBST(root))
cout<<"The given tree is a BST";
else
cout<<"The given tree is Not a BST";
return 0;
}The given tree is a BST
代码解释
上述代码检查一个二叉搜索树。主方法创建一棵树并调用isBST()方法。该方法检查左右子节点是否遵循二叉搜索树规则,并且使用isBSTuntil()方法来检查形成的子树是否也是二叉搜索树。
方法。以上就是一个用C语言编写的程序,用于检查二叉树是否为二叉搜索树(BST)的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号