试设计一个判别给定二叉树是否为二叉排序树的算法。用c语言
时间: 2024-01-14 09:19:55 浏览: 98
写一算法,判断一棵二叉树是否是一棵二叉排序树。
以下是用C语言实现判断给定二叉树是否为二叉排序树的算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int preVal = -2147483648; // 二叉树中序遍历的前一个节点的值,初始化为int类型的最小值
int isValidBST(TreeNode* root) {
if (root == NULL) { // 空树是二叉排序树
return 1;
}
if (!isValidBST(root->left)) { // 遍历左子树
return 0;
}
if (root->val <= preVal) { // 如果当前节点的值小于等于前一个节点的值,说明不是二叉排序树
return 0;
}
preVal = root->val; // 更新前一个节点的值
if (!isValidBST(root->right)) { // 遍历右子树
return 0;
}
return 1; // 是二叉排序树
}
int main() {
// 构造一棵二叉排序树
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 4;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
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 = 3;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 6;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 5;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->right->right->left = NULL;
root->right->right->right = NULL;
if (isValidBST(root)) {
printf("给定二叉树是二叉排序树\n");
} else {
printf("给定二叉树不是二叉排序树\n");
}
return 0;
}
```
阅读全文