树结构练习——排序二叉树的中序遍历
2015-06-21 11:05
471 查看
树结构练习——排序二叉树的中序遍历
Time Limit: 1000ms Memory limit: 65536K
题目描述
在树结构中,有一种特殊的二叉树叫做排序二叉树,直观的理解就是——(1).每个节点中包含有一个关键值 (2).任意一个节点的左子树(如果存在的话)的关键值小于该节点的关键值 (3).任意一个节点的右子树(如果存在的话)的关键值大于该节点的关键值。现给定一组数据,请你对这组数据按给定顺序建立一棵排序二叉树,并输出其中序遍历的结果。
输入
输入包含多组数据,每组数据格式如下。
第一行包含一个整数n,为关键值的个数,关键值用整数表示。(n<=1000)
第二行包含n个整数,保证每个整数在int范围之内。
输出
为给定的数据建立排序二叉树,并输出其中序遍历结果,每个输出占一行。
示例输入
1
2
2
1 20
示例输出
2
1 20
Time Limit: 1000ms Memory limit: 65536K
题目描述
在树结构中,有一种特殊的二叉树叫做排序二叉树,直观的理解就是——(1).每个节点中包含有一个关键值 (2).任意一个节点的左子树(如果存在的话)的关键值小于该节点的关键值 (3).任意一个节点的右子树(如果存在的话)的关键值大于该节点的关键值。现给定一组数据,请你对这组数据按给定顺序建立一棵排序二叉树,并输出其中序遍历的结果。
输入
输入包含多组数据,每组数据格式如下。
第一行包含一个整数n,为关键值的个数,关键值用整数表示。(n<=1000)
第二行包含n个整数,保证每个整数在int范围之内。
输出
为给定的数据建立排序二叉树,并输出其中序遍历结果,每个输出占一行。
示例输入
1
2
2
1 20
示例输出
2
1 20
/* 开始的时候在遍历的时候输出WA,不明所以,后来改成计入数组就对了 */ #include <map> #include <set> #include <cmath> #include <queue> #include <stack> #include <cctype> #include <cstdio> #include <time.h> #include <string> #include <cstring> #include <cstdlib> #include <climits> #include <iostream> #include <algorithm> #define RR freopen("input.txt","r",stdin) #define WW freopen("output.txt","w",stdout) #define INF 0x3f3f3f3f using namespace std; const int Max=10000; int n; int b[1100]; int top; struct Tree { int Data; Tree* Lchild; Tree* Rchild; }* Root; Tree* CreatTree() { Tree* p; p=new Tree; p->Lchild=NULL; p->Rchild=NULL; return p; } void BuildTree(Tree* root,int data)//建立二叉排序树 { if(data<root->Data) { if(root->Lchild) { BuildTree(root->Lchild,data); } else { root->Lchild=CreatTree(); root->Lchild->Data=data; } } else { if(root->Rchild) { BuildTree(root->Rchild,data); } else { root->Rchild=CreatTree(); root->Rchild->Data=data; } } } void InOrder(Tree* root)//进行中序遍历 { if(!root) { return ; } InOrder(root->Lchild); b[top++]=root->Data; InOrder(root->Rchild); } int main() { int a; while(~scanf("%d",&n)) { for(int i=0;i<n;i++) { scanf("%d",&a); if(i) { BuildTree(Root,a); } else { Root=CreatTree(); Root->Data=a; } } top=0; InOrder(Root); for(int i=0; i<top; i++) { if(i) cout<<" "; cout<<b[i]; } cout<<endl; } return 0; }
相关文章推荐
- 树结构练习——排序二叉树的中序遍历 分类: 树 2015-06-21 11:05 12人阅读 评论(0) 收藏
- Java并发编程-33-线程安全的可遍历映射
- 开始在linux下做c语言开发
- Effective C++条款16:成对使用new和delete时要采取相同形式
- 公司如何调薪才能让员工满意
- 据说年薪30万的Android程序员必须知道的帖子【转载】
- 第一章 为什么要学习编写程序?
- Appium Android ——利用 TestNG 并行执行用例
- 配置Spring AOP,XML方式比Annotation方式略好
- 第一章 为什么要学习编写程序?
- CXF(2.7.10) - Writing a service with Spring
- 【转】趣写算法系列之--匈牙利算法
- 数据结构实验之二叉树的建立与遍历
- SGU 223 Little Kings
- ios:关于ASIHTTP:setDownloadProgressDelegate代理不声明协议的问题(已解决)
- django 简单会议室预约(1)
- 数据结构实验之二叉树的建立与遍历 分类: 树 2015-06-21 11:02 8人阅读 评论(0) 收藏
- Path Sum算法详解
- 2015华为软赛(一)——环境
- HDU 5272 解题报告