7-5 Binary Search Tree

【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;
}

 

  • 17
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值