用C++语言写一个通过中序遍历判断是否为二叉搜索树的代码
时间: 2023-06-03 15:07:51 浏览: 145
好的,以下是用 C 语言编写的通过中序遍历判断是否为二叉搜索树的代码:
```c
#include <stdio.h>
#include <stdbool.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 判断二叉树是否为二叉搜索树
bool isValidBST(TreeNode* root) {
static TreeNode* prev = NULL;
if (root == NULL) {
return true;
}
if (!isValidBST(root->left)) {
return false;
}
if (prev != NULL && prev->val >= root->val) {
return false;
}
prev = root;
return isValidBST(root->right);
}
// 中序遍历二叉树
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
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;
// 输出中序遍历序列
printf("中序遍历序列为:");
inorderTraversal(root);
printf("\n");
// 判断是否为二叉搜索树并输出结果
bool result = isValidBST(root);
printf("是否为二叉搜索树:%s\n", result ? "是" : "否");
return 0;
}
```
该代码中,isValidBST 函数通过递归方式中序遍历二叉树,并记录上一个访问的节点 prev,判断当前节点和 prev 的值大小关系是否符合二叉搜索树的定义。如果符合,更新 prev 的值为当前节点,继续访问右子树。如果不符合,返回 false,代表该二叉树不是二叉搜索树。而 inorderTraversal 函数则是为了输出中序遍历序列方便代码测试。
阅读全文
相关推荐
















