CheckBST[1]
来源:互联网 发布:centos 开启组播 编辑:程序博客网 时间:2024/06/05 10:29
Given a binary tree, you are supposed to tell if it is a binary search tree. If the answer is yes, try to find theKKK-th largest key, else try to find the height of the tree.
Format of function:
int CheckBST ( BinTree T, int K );
where BinTree
is defined as the following:
typedef struct TNode *BinTree;struct TNode{ int Key; BinTree Left; BinTree Right;};
The function CheckBST
is supposed to return the K
-th largest key ifT
is a binary search tree; or if not, return the negative height of T
(for example, if the height is 555, you must return −5-5−5).
Here the height of a leaf node is defined to be 1. T
is not empty and all its keys are positive integers.K
is positive and is never more than the total number of nodes in the tree.
Sample program of judge:
#include <stdio.h>#include <stdlib.h>typedef struct TNode *BinTree;struct TNode{ int Key; BinTree Left; BinTree Right;};BinTree BuildTree(); /* details omitted */int CheckBST ( BinTree T, int K );int main(){ BinTree T; int K, out; T = BuildTree(); scanf("%d", &K); out = CheckBST(T, K); if ( out < 0 ) printf("No. Height = %d\n", -out); else printf("Yes. Key = %d\n", out); return 0;}/* 你的代码将被嵌在这里 */
Sample Input 1: (for the following tree)
4
Sample Output 1:
Yes. Key = 5
Sample Input 2: (for the following tree)
3
Sample Output 2:
No. Height = 3
result:
CheckBST ( BinTree T, int K ){ int situation=1; BinTree queue[201]; BinTree M; int a[201]; int i; int Front,rear; int height=0; int max; int times=K; int ai=1; Front=1; rear=1; queue[1]=T; rear++; if(T->Left==NULL&&T->Right==NULL) return T->Key; while(Front!=rear) { if(queue[Front]!=NULL) { queue[rear]=queue[Front]->Left; rear++; queue[rear]=queue[Front]->Right; rear++; } Front++; } for(i=1;i<rear;i++) { if(queue[i]==NULL) continue; if(queue[i]->Left!=NULL) { M=queue[i]->Left; while(M->Right!=NULL) M=M->Right; if(M->Key>queue[i]->Key) { situation=2; break; } } if(queue[i]->Right!=NULL) { M=queue[i]->Right; while(M->Left!=NULL) M=M->Left; if(M->Key<queue[i]->Key) { situation=2; break; } } } if(situation==2) { rear--; while(rear!=0) { rear=rear/2; height++; } height=-height; return height; } else { Front--; for(i=1;i<=Front;i++) if(queue[i]!=NULL) { a[ai]=queue[i]->Key; ai++; } max=1; while(times!=0) { for(i=1;i<=ai;i++) { if(a[max]<a[i]) max=i; } times--; if(times!=0) a[max]=0; } return a[max]; }}
0 0
- CheckBST[1]
- CheckBST[1] ___PTA
- week5 4-1 CheckBST[1]
- 1
- 1
- 1
- 1
- 1
- 1
- 1》
- 1
- 1
- 1
- 1
- (1)
- 1
- 1
- 1
- 实现自动回复
- linux内核源码总览之二---------mm目录
- linux串口雷区
- cisco交换机配置(一)
- 计算几何之多边形
- CheckBST[1]
- Tomcat目录结构及配置文件说明
- C语言学习日记10
- Android 退出键的监听
- notepad++ 设置轻量级编译器
- ExtJS4组件_button按钮配置-属性-方法详解
- unity中用vs或mono编译器编写的脚本在unity中不能被更新
- 微信调用第三方API
- php socket_recv 和 socket_read