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:也可以用线段树建树的。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值