HDU 3791 二叉搜索树

本文介绍了一种通过数字序列构建二叉树的方法,并通过比较两个数字序列构建的二叉树来判断它们是否相同。使用C++实现算法,详细展示了如何根据数字的大小关系确定节点的位置。

题意:给出两串数字,每一串数字都构成一颗二叉树,问这两颗二叉树是否为同一颗二叉树。

可以用样例来考虑

5 6 7 4 3 2 6

6大于5,6是5的右儿子

7大于5,大于6,所以是5的右儿子的右儿子,即为6的右儿子

4小于5,所以4是5的左儿子

画出这一颗二叉树为

 1 #include<iostream>  
 2 #include<cstdio>  
 3 #include<cstring> 
 4 #include <cmath>   
 5 #include<algorithm>  
 6 using namespace std;
 7 
 8 typedef long long LL;
 9 char s[25],s1[25];
10 int tree[2025],tree1[2025];
11 
12 int main()
13 {
14     int t,i,j;
15     while(scanf("%d",&t)!=EOF&&t){
16         memset(tree,-1,sizeof(tree));
17         cin>>s;
18         for(i=0;i<strlen(s);i++){
19             int c=s[i]-'0';
20             j=1;
21             while(tree[j]!=-1){
22                 if(c<=tree[j]) j=2*j;
23                 else j=2*j|1;
24             }
25             tree[j]=c;
26         }
27         
28         while(t--){
29             memset(tree1,-1,sizeof(tree1));
30             cin>>s1;
31            for(i=0;i<strlen(s1);i++){
32             int c=s1[i]-'0';
33             j=1;
34             while(tree1[j]!=-1){
35                 if(c<=tree1[j]) j=2*j;
36                 else j=2*j|1;
37             }
38             tree1[j]=c;
39         }
40         
41         for(i=1;i<=2005&&tree[i]==tree1[i];i++);//注意这里判断i的时候要比开的tree数组的大小小一些,因为这个wrongwrongwrong 
42         if(i>2005) printf("YES\n");
43         else printf("NO\n");
44         }
45     }
46     return 0;
47 }
View Code

 

转载于:https://www.cnblogs.com/wuyuewoniu/p/4334780.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值