二叉排序树
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
NO NO
#include <stdio.h> int flag,n; struct node { char data; struct node *l, *r; }; struct node *creat(char x, struct node *root) { if(!root)//如果树为空 或者 找到合适的位置 新建 根或叶子结点 { root = new node; root->data = x; root->l = root->r = NULL; return root; } if( x < root->data)//如果此时值 此时的根节点值小 则向左递归 root->l = creat(x, root->l); else root->r = creat(x, root->r); return root; }; void judge(struct node *root,struct node *root1) { if(root && root1) { if(root->data != root1->data) { flag = 1;return; } judge(root->l,root1->l); judge(root->r,root1->r); } } int main() { char s[10]; while(~scanf("%d",&n),n) { scanf("%s",s); struct node *root; root = NULL; for( int i = 0; i < 9; i++) { root = creat(s[i], root); } while(n--) { struct node *root1; root1 = NULL; scanf("%s",s); for( int i = 0; i < 9; i++) { root1 = creat(s[i], root1); } //printf("--------\n"); flag = 0; judge(root, root1); if(flag) printf("NO\n"); else printf("YES\n"); } } }