博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
04-树4 是否同一棵二叉搜索树(25 分)---陈越、何钦铭-数据结构-2017秋
阅读量:4047 次
发布时间:2019-05-25

本文共 1876 字,大约阅读时间需要 6 分钟。

04-树4 是否同一棵二叉搜索树(25 分)

给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。

输入格式:

输入包含若干组测试数据。每组数据的第1行给出两个正整数N (≤10)和L,分别是每个序列插入元素的个数和需要检查的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列。最后L行,每行给出N个插入的元素,属于L个需要检查的序列。

简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。

输出格式:

对每一组需要检查的序列,如果其生成的二叉搜索树跟对应的初始序列生成的一样,输出“Yes”,否则输出“No”。

输入样例:

4 2

3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

输出样例:

Yes

No
No

和这个题差不多,都是简单的递归!本题还考察了二叉搜索树的插入

#include
#include
#define ElementType inttypedef struct BiNode { ElementType Element; struct BiNode* Left; struct BiNode* Right;}BiNode, *BiTree;BiTree Insert(ElementType x, BiTree &BST){ if (!BST) { BST = (BiTree)malloc(sizeof(BiNode)); BST->Element = x; BST->Left = BST->Right = NULL; } else if (x < BST->Element) BST->Left = Insert(x, BST->Left); else if (x > BST->Element) BST->Right = Insert(x, BST->Right); return BST;}int IsSame(BiTree T1, BiTree T2){ if (T1 == NULL&&T2 == NULL) return 1; if ((T1 == NULL&&T2 != NULL) || (T1 != NULL&&T2 == NULL)) return 0; if (T1->Element != T2->Element) return 0; return (IsSame(T1->Left, T2->Left) && IsSame(T1->Right, T2->Right));}int main(){ BiTree a; BiTree T; int N1, N2, n; while (1) { scanf("%d", &N1); if (N1 == 0) { break; } scanf("%d", &N2); T = NULL; for (int i = 0; i < N1; i++) //建第一个树 { scanf("%d", &n); Insert(n, T); } for (int i = 0; i < N2; i++) { a = NULL; for (int j = 0; j< N1; j++) { scanf("%d", &n); Insert(n, a); } if (IsSame(T, a))puts("Yes"); else puts("No"); } }//while system("pause");}

转载地址:http://xkyci.baihongyu.com/

你可能感兴趣的文章
[LeetCode By Python]121. Best Time to Buy and Sell Stock
查看>>
[LeetCode By Python]122. Best Time to Buy and Sell Stock II
查看>>
[LeetCode By Python]125. Valid Palindrome
查看>>
[LeetCode By Python]136. Single Number
查看>>
Android/Linux 内存监视
查看>>
Android2.1消息应用(Messaging)源码学习笔记
查看>>
MPMoviePlayerViewController和MPMoviePlayerController的使用
查看>>
CocoaPods实践之制作篇
查看>>
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>
剑指offer算法题分析与整理(三)
查看>>
Ubuntu 13.10使用fcitx输入法
查看>>
pidgin-lwqq 安装
查看>>