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.1
2
3
4
5
6
7
8
9Sample Input:
3 4
1 4 2 3
2 4 1 3
3 2 4 1
Sample Output:
YES
NO
NO
1 | #include<iostream> |
又是一个一遍就AC的代码,不过写的不好,时间复杂度非常高。
思路:
因为是二叉搜索树,必定遵循的原则就是:右>根>左。
举例来说:序列:1
1 4 2 3
4 > 1,意味着4是右子树,同时也意味着4后面所有的元素都是右子树中的元素(注意题目说了这是搜索路径),这就说明4后面的所有元素都要大于1才正确,同理类推,2<4,所以2是4的左子树,2后面所有的元素都要小于4才正确。依次类推,全部符合要求即输出YES,否则输出NO。