用c语言试写一个判别给定二叉树是否为二叉排序树的程序
时间: 2024-02-13 22:03:02 浏览: 112
判别给定二叉树是否为二叉排序树
4星 · 用户满意度95%
以下是用C语言实现的判断二叉树是否为二叉排序树的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
bool isValidBSTHelper(TreeNode* root, int* lower, int* upper) {
if (root == NULL) {
return true;
}
if (lower != NULL && root->val <= *lower) {
return false;
}
if (upper != NULL && root->val >= *upper) {
return false;
}
return isValidBSTHelper(root->left, lower, &root->val) &&
isValidBSTHelper(root->right, &root->val, upper);
}
bool isValidBST(TreeNode* root) {
return isValidBSTHelper(root, NULL, NULL);
}
int main() {
// 构造一个二叉排序树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 5;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 1;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 4;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 7;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 8;
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("输入的二叉树%s是二叉排序树\n", isValidBST(root) ? "" : "不");
return 0;
}
```
程序中使用了递归的方法,isValidBSTHelper函数用于判断以root为根的子树是否为二叉排序树,lower和upper参数分别表示root的值应该在的区间。isValidBST函数则调用了isValidBSTHelper函数,将lower和upper都初始化为NULL,表示不限制。最后在main函数中构造了一个二叉排序树,并输出是否为二叉排序树的结果。
阅读全文