04-Tree 7. Search in a Binary search Tree (25) time limit
Memory Limit 65536 KB
Code length limit 8000 B
Procedures for the award of questions StandardAuthor Chen, Yue
to Search a key in a binary search tree, we start from the root and move all the" the "the" the "and" the ". Choosi NG 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
#include <stdio.h>//search tree requires that all elements on the right side of any element in the path be greater than or less than it;//directly traverse each element, compare the size of the right element, the time complexity is O (n^2), timeout,//o (n) Method: Start at the end of the path , maintaining two variables: the maximum and minimum values for the current trailing element. int Judgepath (int *path, int n) {int min = path[n-1], max = path[n-1];for (int i = n-2; I >= 0; i) {if (Path[i] > Max)//If the current element is larger than the maximum value, indicating that the following path is the left subtree of the current element, the possible max = path[i];//Update max value else if (Path[i] < min) min = path[i];else// The current element is between the maximum and minimum values, not a return of 0;} return 1;} int main () {//freopen ("test.txt", "R", stdin), int n, m;scanf ("%d%d", &n, &m), while (n--) {//n test case int path[100] = {};for (int i = 0; i < m; ++i) {scanf ("%d", &path[i]);} if (Judgepath (path, M)) printf ("yes\n"); elseprintf ("no\n");} return 0;}
Title Link: http://www.patest.cn/contests/mooc-ds/04-%E6%A0%917
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
04-Tree 7. Search in a Binary search Tree (25)