HDU 3791 二叉搜索树

27 篇文章 0 订阅
12 篇文章 0 订阅

二叉搜索树

Time Limit: 2000/1000 MS (Java/Others)Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 218Accepted Submission(s): 96

Problem Description
判断两序列是否为同一二叉搜索树序列

 

Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。

 

Output
如果序列相同则输出YES,否则输出NO

 

Sample Input
 
 
2 567432 543267 576342 0

 

Sample Output
 
 
YES NO

 

Source

 

Recommend
notonlysuccess

 

睇个名就知道同埋二叉树有关………………

其实思路好简单,按顺序插入数字之后,再用二叉树先、中序或者,中、后序表达式判断两颗二叉树系唔系相同,原理可以问百度谷歌维基。

其实可以拿我博客果篇多功能二叉树直接模版过,不过我换左一种写法…………

 

下面贴代码:

 

43127162011-08-02 14:19:44Accepted37910MS208K1416 BC++10SGetEternal{(。)(。)}!

 

#include <iostream> #include <string> using namespace std; #define MAXI 11 class BST { public : struct node { int key; node *son[2]; } *root, space[3 * MAXI]; int id; void Init() { root = NULL; id = 0; } void Bulid(char *s) { int i; Init(); for (i = 0; i < strlen(s); i++) Insert(s[i]); } void Create(node *&x, int key) { x = &space[id++]; x->key = key; x->son[0] = NULL; x->son[1] = NULL; } void Insert(int key) { bool lr; node *x = root, *y, *w; if (root == NULL) { Create(root, key); return ; } while (x != NULL) { y = x; lr = key > x->key; x = x->son[lr]; } Create(w, key); y->son[lr] = w; } void Ftra(node *x, string &s) { if (x == NULL) return ; s += x->key; Ftra(x->son[0], s); Ftra(x->son[1], s); } void Mtra(node *x, string &s) { if (x == NULL) return ; Mtra(x->son[0], s); s += x->key; Mtra(x->son[1], s); } bool operator == (BST o) { string s1, s2; Ftra(root, s1); Ftra(o.root, s2); if (s1 != s2) return 0; Mtra(root, s1); Mtra(o.root, s2); if (s1 != s2) return 0; return 1; } }zkl, tzk; int main() { int n; char ch[MAXI]; while (scanf("%d", &n), n) { scanf("%s", ch); zkl.Bulid(ch); while (n--) { scanf("%s", ch); tzk.Bulid(ch); puts(zkl == tzk? "YES": "NO"); } } return 0; }

 

其实关于二叉树,可以出得更加水生气

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值