二叉搜索树判断代码
2025-12-20 20:31:03
发布于:广东
#include <iostream>
using namespace std;
const int SIZE = 100;
const int INFINITE = 1000000;
struct node {
int left_child, right_child, value;// 左节点,右节点,根节点值
};
node a[SIZE];
int is_bst(int root, int lower_bound, int upper_bound){//根节点,下界,上界
int cur;//临时取值:根节点的值(类比二分查找的mid)
if (root == 0) return 1;//特判:根节点最小
cur = a[root].value;//出口是根节点的值
if ((cur > lower_bound) && (cur < upper_bound) && (is_bst(a[root].left_child, lower_bound, cur) == 1) && (is_bst(a[root].right_child, cur, upper_bound) == 1) ) return 1;
//判定方法:二叉搜索树性质1 && 性质2 && 性质3
return 0;
}
int main(){
int i,n;
cin >> n;
for(int i = 1;i <= n;i++) cin >> a[i].value >> a[i].left_child >> a[i].right_child;
cout << is_bst(1 ,-INFINITE,INFINITE) << endl;//从根节点下标(1)开始
return 0;
}
这里空空如也












有帮助,赞一个