二叉搜索树
Time Limit: 2000/1000 MS (Java/Others)Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 218Accepted Submission(s): 96
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
睇个名就知道同埋二叉树有关………………
其实思路好简单,按顺序插入数字之后,再用二叉树先、中序或者,中、后序表达式判断两颗二叉树系唔系相同,原理可以问百度谷歌维基。
其实可以拿我博客果篇多功能二叉树直接模版过,不过我换左一种写法…………
下面贴代码:
4312716 | 2011-08-02 14:19:44 | Accepted | 3791 | 0MS | 208K | 1416 B | C++ | 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; }
其实关于二叉树,可以出得更加水。