7-6 Traverse Binary Search Tree

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.

Given a sequence of distinct integers to build the binary search tree, and traverse the tree by Preorder.

输入格式:

1line.
The line gives a sequence of distinct integers. These integers are separated by commas. The binary search tree must be built according to the input order of these integers.

输出格式:

1 line.
One sequence of integers separated by commas. The sequence is the traversal result of the Preorder.

输入样例:

在这里给出一组输入。例如:

4,2,6,1,3,5,7,

输出样例:

在这里给出相应的输出。例如:

4,2,1,3,6,5,7,

C语言代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.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;
}

void preorder(struct Node * Tree){
    if(!Tree) return;
    printf("%d,",Tree->data);
    preorder(Tree->Left);
    preorder(Tree->Right);
}

main(){
    struct Node * Tree=NULL;
    char string[2000];
    int i;
    fgets(string,2000,stdin);
    for(i=0;i<strlen(string)-1;i++){
        int num=0;
        while(string[i]!=','){
            num=num*10+string[i]-'0';
            i++;
        }
        Tree=Insert(num,Tree);
    }
    preorder(Tree);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值