【Definition】A binary search tree is a binary tree. It may be empty. If it is not empty, it satisfies the following properties:
(1) Every node has a key which is an integer, and the keys are distinct.
(2) The keys in a nonempty left subtree must be smaller than the key in the root of the subtree.
(3) The keys in a nonempty right subtree must be larger than the key in the root of the subtree.
(4) The left and right subtrees are also binary search trees.
Give a sequence of distinct integer to build the binary search tree, and output the nodes on particular level.
输入格式:
3 lines.
The first line means the number of sequence. This number is more than 1 and less than 20.
The second line gives the sequence of distinct integer. The integers are divided by comma. You must build the tree according to the input order.
The third line means the number of level(>=1). The root node is located on level 1. And the children of the root is located on level 2. And so on.
输出格式:
1 line.
A sequence of numbers divided by comma. The numbers represent the nodes on the given level from left to right.
If there is no node on the level, then output -1.
输入样例:
在这里给出一组输入。例如:
10
32,3,56,4,75,53,33,76,90,2,
3
输出样例:
在这里给出相应的输出。例如:
2,4,53,75,
C语言代码:
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node * Left;
struct Node * Right;
};
struct Node * CreateNode(int key){
struct Node * T;
T=(struct Node * )malloc(sizeof(struct Node ));
T->data=key;
T->Left=NULL;
T->Right=NULL;
return T;
}
struct Node * Insert(int key,struct Node * T){
if(!T){
T=CreateNode(key);
return T;
}
if(key<T->data) T->Left=Insert(key,T->Left);
if(key>=T->data) T->Right=Insert(key,T->Right);
return T;
}
int downinto(struct Node * T,int aim,int curpos){
if(T==NULL) return 0;
if(curpos==aim){
printf("%d,",T->data);
return 1;
}
if(curpos<aim){
int flag1,flag2;
flag1=downinto(T->Left,aim,curpos+1);
flag2=downinto(T->Right,aim,curpos+1);
return flag1||flag2;
}
}
main(){
struct Node * Tree=NULL;
int N;
scanf("%d",&N);
int i;
for(i=0;i<N;i++){
int num;
scanf("%d,",&num);
Tree=Insert(num,Tree);
}
int aim;
scanf("%d",&aim);
int flag;
flag=downinto(Tree,aim,1);
if(!flag) printf("-1");
return 0;
}