码迷,mamicode.com
首页 > 其他好文 > 详细

PAT Search in a Binary Search Tree

时间:2015-05-23 22:30:29      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

Search in a Binary Search Tree

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.

 

首先 理解题意 给出一个序列  每一个数都是前一个数的左右儿子之一  保证这棵树是搜索树

这道题其实是考察搜索二叉树的建立 我用了个取巧的方法 并没有建二叉树  凡是满足题意的序列 有一个规律 

若第二个数比第一个数大 那后面的所有数都比第一个数大  若第三个数比第二个数小 那第三个数以后的数都比第二个数小

以{1,4,2,3}为例子 大家可以验证一下

至于为什么有这个规律 大家想一下搜索二叉树的定义就知道了

下面给出AC代码

 1 #include "stdio.h"
 2 main()
 3 {
 4     int m,n;
 5     scanf("%d%d",&m,&n);
 6     int i,j,k,flag;
 7     int a[100];
 8     for(i=0;i<m;i++)
 9     {    
10         flag=0;
11         for(j=0;j<n;j++)
12         {
13             scanf("%d",&a[j]);
14         }
15         for(k=0;k<n-1;k++)
16         {
17             if(a[k+1]>a[k])
18             {
19                 for(j=k+1;j<n;j++)
20                 {
21                     if(a[j]<=a[k])
22                     {
23                         flag=-1;break;
24                     }    
25                 }
26             }
27             else
28             {
29                 for(j=k+1;j<n;j++)
30                 {
31                     if(a[j]>=a[k])
32                     {
33                         flag=-1;
34                         break;
35                     }    
36                 }
37             }
38         }
39         if(flag==-1)
40             printf("NO\n");
41         else
42             printf("YES\n");
43     }
44     
45 }

 

PAT Search in a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/threezj/p/4525014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!