二叉排序树
来源:互联网 发布:韩孝珠李钟硕 知乎 编辑:程序博客网 时间:2024/05/22 08:24
二叉排序树
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
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
Hint
Author
PS:
二叉排序树,左孩子小于当前根节点,右孩子大于当前根节点,按照此顺序递归建树;验证两棵树是否相同,只需要让他们有序排列后看看是否相同,即可得证。
AC code:
#include<bits/stdc++.h>using namespace std;struct node{ char data; struct node *lc, *rc;};void creat(struct node *&root, char st){ if(root==NULL) { root= new node; root->lc=NULL; root->rc=NULL; root->data= st; } else { if(st < root->data) creat(root->lc,st); else creat(root->rc,st); }}int i = 0;char st2[100] = {0}, st3[100] = {0};void qianxu(struct node * root){ if(root) { st2[i++] = root->data; qianxu(root->lc); qianxu(root->rc); }}int j = 0;void houxu(struct node * root){ if(root) { houxu(root->lc); houxu(root->rc); st3[j++] = root->data; }}int main(){ int n; while(cin>>n) { if(n == 0) break; char st[100] = {0}, st1[100] = {0}; struct node* root = NULL; cin>>st; int len = strlen(st); for(int i = 0; i < len; i++) { creat(root, st[i]); } qianxu(root); houxu(root); j = 0; i = 0; while(n--) { cin>>st1; if(strcmp(st1, st) == 0) cout<<"YES"; else if(strcmp(st1, st2) == 0) cout<<"YES"; else if(strcmp(st1, st3) == 0) cout<<"YES"; else cout<<"NO"; cout<<endl; } memset(st2,0,sizeof(st2)); memset(st3,0,sizeof(st3)); } return 0;}/***************************************************User name: Result: AcceptedTake time: 0msTake Memory: 156KBSubmit time: 2017-02-13 20:10:55****************************************************/
阅读全文
0 0
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 中国式穷人思维
- 常量指针和指针常量的区别详解
- 6.面向对象的基础
- leetcode--3Sum Closest
- android jni 返值
- 二叉排序树
- [Suzuki85]轮廓跟踪算法论文翻译
- leetcode--Letter Combinations of a Phone Number
- 启动redis报Aug 02:14:28
- 大数据
- Kettle 资源库-保存Kettle 元数据
- 递推:兔子产子
- BIO与NIO、AIO的区别
- 面向对象的三大特点