To search a key in a binary search tree, we start from the root and move all the 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} are not such a path since 1 are in the right subtree of the root 2, which breaks the rule for a binary sear Ch Tree. Now given a sequence of keys, you is supposed to tell whether or not it indeed correspnds to a searching path in a binary Search tree.
Input Specification:
Each input file contains the one test case. The first line gives positive integers N and M (<=100) which is 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, the keys numbered from 1 to M.
Output Specification:
For each sequence, print with a line "YES" if the sequence does correspnd to a searching path in a binary search tree, or "N O "if not.
Sample Input:
3 41 4 2 32 4 1 33 2 4 1
Sample Output:
Yesnono
Problem-solving ideas: If the number of i+1 is larger than I (small), the number behind the i+1 is greater than I (small)
To solve the problem: You can use the flag to jump out of two for loop
1#include <iostream>2#include <vector>3 using namespacestd;4 intMain () {5 intN, M;6CIN >> N >>m;7 for(inti =0; I < n;i++)8 {9 intFlag =0;Tenvector<int>v; One for(intj =0; J < m;j++) A { - intElem; -CIN >>Elem; the V.push_back (elem); - } - for(intj =0; J < M-2; j + +) - { + if(V[j]>v[j +1]) - { + for(intK = j +2; K < m;k++) A { at if(v[k]>=V[j]) - { -Flag =1; - Break; - } - } in } - Else to { + for(intK = j +2; K < M; k++) - { the if(V[k] <=V[j]) * { $Flag =1;Panax Notoginseng Break; - } the } + } A if(Flag = =1) the Break; + } - if(Flag = =1) $cout <<"NO"<<Endl; $ Else -cout <<"YES"<<Endl; - } the return 0; -}
Search in a Binary search Tree