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