二叉排序树
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
Output
Example Input
2 123456789 987654321 432156789 0
Example Output
NONO
解题关键:一棵二叉树可以由其先序和中序或者后序和中序唯一确定。因此比较两棵树是否相同。可以使用字符串比较函数strcmp()。
#include<stdio.h> #include<iostream> #include<stdlib.h> #include<string.h> using namespace std; typedef struct BiTNode{ int data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; char a[100], b[100]; char I1[100], P1[100], I2[100], P2[100]; int N; void create(BiTree &T, int n) { if (T) { if (T->data < n) create(T->lchild, n); else create(T->rchild, n); } else { T = (BiTNode *)malloc(sizeof(BiTNode)); T->data = n; T->lchild = NULL; T->rchild = NULL; } } void InOrder(BiTree &T, char I[]) { if (T) { InOrder(T->lchild, I); I[N++] = T->data; InOrder(T->rchild, I); } } void PosOrder(BiTree &T, char P[]) { if (T) { PosOrder(T->lchild, P); PosOrder(T->rchild, P); P[N++] = T->data; } } int main() { int n, l; while (cin>>n, n) { memset(a, 0, sizeof(a)); scanf("%s", a); BiTree T1; T1 = NULL; l = strlen(a); for (int i = 0; i < l; i++) { create(T1, a[i]); } N = 0; InOrder(T1, I1); I1[N] = '\0';//注意这里给定边界必不可少 N = 0; PosOrder(T1, P1); P1[N] = '\0'; while (n--) { memset(b, 0, sizeof(b)); scanf("%s", b); if (strlen(a) - strlen(b)) printf("NO\n"); else { BiTree T2; T2 = NULL; for (int i = 0; i < l; i++) { create(T2, b[i]); } N = 0; InOrder(T2, I2); I2[N] = '\0'; N = 0; PosOrder(T2, P2); P2[N] = '\0'; if (strcmp(I1, I2) || strcmp(P1, P2)) printf("NO\n"); else printf("YES\n"); } } } return 0; }