二叉查找树具有如下性质:
每个节点的值都大于其左子树上所有节点的 值、
小于其右子树上所有节点的值。
试判断一棵树是否为二叉查找树。
输入的第一行包含一个整数 n,
表示这棵树有 n 个顶点,
编号分别为 1, 2, ? , n,其 中编号为 1 的为根结点。
之后的第 i 行有三个数 value, left_child , right_child ,
分别表示该节点关键字的值、左子节点的编号、右子节点的编号;
如果不存在左子节点或右子节点,则用 0 代替。
输出
1 表示这棵树是二叉查找树,
输出0 则表示不是。
#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;
if ( root == 0 )
return(1);
cur = a[root].value;
//① cur < upper_bound
if ( (cur > lower_bound) && ( ① ) &&
(is_bst( a[root].left_child, lower_bound, cur ) == 1)
&& (is_bst( ②, ③, ④ ) == 1) )
return(1);
// ② a[root].right_child
// ③cur
// ④upper_bound
return(0);
}
int main()
{
int i, n; cin >> n;
for ( i = 1; i <= n; i++ )
cin >> a[i].value >> a[i].left_child >> a[i].right_child;
cout << is_bst( ⑤, -INFINITE, INFINITE ) << endl;
return(0);
}
/*
1.正确答案: cur < upper_bound
2.正确答案: a[root].right_child
3.正确答案: cur
4.正确答案: upper_bound
5.正确答案: 1
*/
初赛试题:完善程序题
NOIP 提高组 初赛 三、问题求解 习题集NOIP1995-NOIP2018
NOIP普及组2006-2018初赛 2019 CSP-J1 2020 CSP-J1 完善程序题
NOIP2006-2018 提高组 初赛试题完善程序题 CSP-S 2019 2020 初赛试题完善程序题
NOIP2006-2018 提高组 初赛试题完善程序题 CSP-S 2019 2020 初赛试题完善程序题_dllglvzhenfeng的博客-CSDN博客
【NOIP2007 普及组】 问题求解题 (子集划分)+Floyd算法
NOIP 2008 普及组初赛试题完善程序 4.2 (找第k大的数)
NOIP 2010 普及组 初赛试题 完善程序 4.1 哥德巴赫猜想
NOIP 2010 普及组初赛试题完善程序4.2(过河问题)
NOIP 2012 提高组初赛试题 完善程序题 5.2 新壳栈
NOIP 2016 普及组初赛试题_完善程序 4.2 郊游活动
NOIP 2017 提高组初赛试题_完善程序 5.1 大整数除法
NOIP 2017 普及组初赛试题_完善程序 4.2:切割绳子
NOIP2018初赛普及组完善程序题第2题(4.2) 第 23 题