输入两段数字,问这两段数字分别构造的二叉排序树是否为相同的两颗树
思路:中序遍历+其他两种遍历中的任何一种遍历可以确定一棵树,比较两棵树的中序遍历+前/后遍历序列,相同则是,不同则否。
代码:
#include<iostream> #include<string> using namespace std; struct node { node* lchild; node* rchild; char c; }tree[110]; int cnt; string s1,b1,s2; string* s;//工作指针 void midorder(node*T) { if (T->lchild != NULL) midorder(T->lchild); s->push_back(T->c); if (T->rchild != NULL) midorder(T->rchild); } void firstorder(node* T) { s->push_back(T->c); if (T->lchild != NULL) firstorder(T->lchild); if (T->rchild != NULL) firstorder(T->rchild); } node* creat() { tree[cnt].lchild = tree[cnt].rchild = NULL; return &tree[cnt++]; } node* insert(node* T, char x) { if (T == NULL) { T = creat(); T->c = x; return T; } else if (x < T->c) T->lchild = insert(T->lchild, x); else if (x > T->c) T->rchild = insert(T->rchild, x); return T; } int main() { int n; while (cin >> n) { if (n == 0)break; cin >> s1; node* T = NULL; cnt = 0; for (int i = 0; i < s1.length(); i++) { T = insert(T, s1[i]); } s = &b1; firstorder(T); midorder(T); while (n--) { cin >> s2; node* T2 = NULL; string b2;//这里注意定义局部变量保存每次遍历的结果,因为我用的push_back填入b2,定义全局变量b2会把之前的数据也保存下来 for (int i = 0; i < s2.length(); i++) { T2 = insert(T2, s2[i]); } s = &b2; firstorder(T2); midorder(T2); if (b1 == b2) cout << "YES" << endl; else cout << "NO" << endl; } } return 0; }