判断两个二叉搜索树序列是否一致
2014-08-16 21:46
281 查看
题目描述:
判断两序列是否为同一二叉搜索树序列
输入:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出:
如果序列相同则输出YES,否则输出NO
样例输入:
样例输出:
[/code]
判断两序列是否为同一二叉搜索树序列
输入:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出:
如果序列相同则输出YES,否则输出NO
样例输入:
2 567432 543267 576342 0
样例输出:
YES NO
分析:现根据输入序列,构建二叉搜索树,然后使用中序和后序,或中序和前序,遍历两个二叉树;若遍历结果相同,则是。
包含中序的两种遍历方式,可确定一个二叉树。
#include<stdio.h> #include<string.h> struct Node { Node *lChild; Node *rChild; char digit; }tree[25]; int alloc; Node * createNode() { tree[alloc].lChild=tree[alloc].rChild=NULL; return &tree[alloc++]; } Node *insert(Node *T, char c) //插入节点 { if(T==NULL) { T=createNode(); T->digit=c; return T; } else if(T->digit>c) T->lChild=insert(T->lChild,c); else if(T->digit<c) T->rChild=insert(T->rChild,c); return T; } char postAndin[25]; //后序和中序遍历序列的连接 int size; //postAndin的大小 char input[25],test[25]; //输入和测试序列 char inputResult[25],testResult[25]; //输入和测试序列的遍历结果 int n; //测试序列个数 void post_order(Node *T) { if(T->lChild) post_order(T->lChild); if(T->rChild) post_order(T->rChild); postAndin[size++]=T->digit; } void in_order(Node *T) { if(T->lChild) in_order(T->lChild); postAndin[size++]=T->digit; if(T->rChild) in_order(T->rChild); } int main() { while(scanf("%d",&n)!=EOF) { if(n==0) break; scanf("%s",&input); Node *T=NULL; int i=0; alloc=0; while(input[i]!=0) T=insert(T,input[i++]); size=0; post_order(T); in_order(T); postAndin[size]=0; //字符数组末尾加上\0 strcpy(inputResult,postAndin); //printf("原始串的后序+中序:%s\n",postAndin); while(n--) { scanf("%s",&test); Node *T2=NULL; int i=0; alloc=0; while(test[i]!=0) T2=insert(T2,test[i++]); size=0; post_order(T2); in_order(T2); postAndin[size]=0; if(strcmp(postAndin,inputResult)==0) printf("YES\n"); else printf("NO\n"); } } return 0; }
[/code]
相关文章推荐
- 判断两个序列构成二叉搜索树是否相同
- 剑指offer题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
- Java 判断栈的push和pop序列是否一致
- 软件设计艺术大师基础--判断序列是否为二叉搜索树的后序遍历序列
- 剑指offer:二叉搜索树的后序遍历序列(判断一个数组是否是二叉搜索树的后续遍历序列)
- 判断数组是否是二叉搜索树的后序遍历序列 JAVA实现
- Interview----判断整数序列是否是二叉搜索树的后序遍历结果
- Arrays - 判断两个数组是否一致 以及常用的判断
- 输入一个数列,判断是否为某一个二叉搜索树的后序遍历序列
- Interview----判断整数序列是否是二叉搜索树的后序遍历结果
- 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
- 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
- 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序
- 判断某序列是否为某二叉搜索树的后序遍历
- 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一
- 给定两个字符串a和b,判断b是否是a的子序列,例如a=”abndjs“,b=“and”则返回ture,如果b=”adn“,那么返回false
- 判断两序列是否为同一棵二叉搜索树
- 判断给定的数组是否为二叉搜索树的后序遍历序列
- 剑指offer——判断一个序列是否为二叉搜索树的后序遍历
- 九度1009判断两个序列构成的两个二叉排序树是否相同