Search in a Binary Search Tree

本文提供了一种方法来判断给定的序列是否对应于二叉搜索树的查找路径。通过检查序列中相邻元素之间的关系,确定序列是否符合二叉搜索树查找路径的规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

To search a key in a binary search tree, we start from the root and move all the way down, choosing branches according to the comparison results of the keys. The searching path corresponds to a sequence of keys. For example, following {1, 4, 2, 3} we can find 3 from a binary search tree with 1 as its root. But {2, 4, 1, 3} is not such a path since 1 is in the right subtree of the root 2, which breaks the rule for a binary search tree. Now given a sequence of keys, you are supposed to tell whether or not it indeed correspnds to a searching path in a binary search tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N and M (<=100) which are the total number of sequences, and the size of each sequence, respectively. Then N lines follow, each gives a sequence of keys. It is assumed that the keys are numbered from 1 to M.

Output Specification:

For each sequence, print in a line "YES" if the sequence does correspnd to a searching path in a binary search tree, or "NO" if not.

Sample Input:

3 4
1 4 2 3
2 4 1 3
3 2 4 1

Sample Output:

YES
NO
NO

解题思路:如果第i+1个数比i个数大(小),i+1后面的数都比i大(小)
解题感悟:可以用标志位连续跳出两个for循环

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main(){
 5     int n, m;
 6     cin >> n >> m;
 7     for (int i = 0; i < n;i++)
 8     {
 9         int flag = 0;
10         vector<int> v;
11         for (int j = 0; j < m;j++)
12         {
13             int elem;
14             cin >> elem;
15             v.push_back(elem);
16         }
17         for (int j = 0; j < m - 2;j++)
18         {
19             if (v[j]>v[j + 1])
20             {
21                 for (int k = j + 2; k < m;k++)
22                 {
23                     if (v[k]>=v[j])
24                     {
25                         flag = 1;
26                         break;
27                     }
28                 }
29             }
30             else
31             {
32                 for (int k = j + 2; k < m; k++)
33                 {
34                     if (v[k] <= v[j])
35                     {
36                         flag = 1;
37                         break;
38                     }
39                 }
40             }
41             if (flag == 1)
42                 break;
43         }
44         if (flag == 1)
45             cout << "NO"<<endl;
46         else
47             cout << "YES"<<endl;
48     }
49     return 0;
50 }

 

 

转载于:https://www.cnblogs.com/lkyblog/p/4422685.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值