hdu 3999(二叉排序树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3999

思路:创建一颗二叉排序树,直接先序遍历即可。

View Code
 1 #include<iostream>
 2 using namespace std;
 3 bool first;
 4 
 5 struct BST{
 6     int data;
 7     BST *leftchild;
 8     BST *rightchild;
 9 };
10 
11 void Build(BST *&root,int x){
12     if(root==NULL){
13         root=(BST *)malloc(sizeof(BST));
14         root->data=x;
15         root->leftchild=root->rightchild=NULL;
16     }else {
17         if(x<root->data){
18             Build(root->leftchild,x);
19         }else 
20             Build(root->rightchild,x);
21     }
22 }
23 
24 void Search(BST *root){
25     if(root!=NULL&&first){
26         first=false;
27         printf("%d",root->data);
28         Search(root->leftchild);
29         Search(root->rightchild);
30     }else if(root!=NULL){
31         printf(" %d",root->data);
32         Search(root->leftchild);
33         Search(root->rightchild);
34     }
35 }
36 
37 
38 int main(){
39     int n;
40     while(~scanf("%d",&n)){
41         BST *root=NULL;
42         first=true;
43         for(int i=1;i<=n;i++){
44             int x;
45             scanf("%d",&x);
46             Build(root,x);
47         }
48         Search(root);
49         printf("\n");
50     }
51     return 0;
52 }

PS:也可以用线段树建树的。。。

原文地址:https://www.cnblogs.com/wally/p/3002094.html