您好,欢迎访问一九零五行业门户网

一个用C语言编写的程序,用于检查二叉树是否为二叉搜索树(BST)

二叉树是一种树形数据结构,每个节点都有两个子节点。这两个子节点被称为左子节点和右子节点。
二叉搜索树(bst)是一种树形结构,其中左子树包含小于根节点的值的节点,右子树包含大于根节点的值的节点。
在这里,我们将检查一个二叉树是否是bst:
为了检查这个,我们需要在二叉树上检查bst条件。对于根节点,左子节点的值应该小于根节点的值,右子节点的值应该大于根节点的值,对于树中所有存在子节点的节点都要满足这个条件。
检查一个二叉树是否是bst的程序#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)的详细内容。
其它类似信息

推荐信息