树结构练习——排序二叉树的中序遍历
2017-08-16 20:26
218 查看
Problem Description
在树结构中,有一种特殊的二叉树叫做排序二叉树,直观的理解就是——(1).每个节点中包含有一个关键值 (2).任意一个节点的左子树(如果存在的话)的关键值小于该节点的关键值 (3).任意一个节点的右子树(如果存在的话)的关键值大于该节点的关键值。现给定一组数据,请你对这组数据按给定顺序建立一棵排序二叉树,并输出其中序遍历的结果。
Input
输入包含多组数据,每组数据格式如下。第一行包含一个整数n,为关键值的个数,关键值用整数表示。(n<=1000)
第二行包含n个整数,保证每个整数在int范围之内。
Output
为给定的数据建立排序二叉树,并输出其中序遍历结果,每个输出占一行。
Example Input
1 2 2 1 20
Example Output
2 1 20
//二叉排序树 #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct tree { int data; struct tree *lc, *rc; } BiTree; int flag; void Add(BiTree *T, int x) //将x插入树 { BiTree *p; p = (BiTree*)malloc(sizeof(BiTree)); if(T->data > x) //T->data大于x,将x插入T的左子树 { if(T->lc == NULL) //T的左子树若为空则建立它的左子树 { p->data = x; p->lc = NULL; p->rc = NULL; T->lc = p; } else //T的左子树不为空则递归Add函数继续比较 Add(T->lc, x); } else //对右子树的操作 { if(T->rc == NULL) { p->data = x; p->lc = NULL; p->rc = NULL; T->rc = p; } else Add(T->rc, x); } } BiTree *Creat(int n) { BiTree *head; int i, x; scanf("%d", &x); head = (BiTree*)malloc(sizeof(BiTree)); //先取出一个数建立head节点 head->data = x; head->lc = head->rc = NULL; for(i = 1; i < n; i++) { scanf("%d", &x); Add(head, x); } return head; } void Show(BiTree *T) //中序遍历 { if(T) { Show(T->lc); if(flag) { printf("%d", T->data); flag = 0; } else printf(" %d", T->data); Show(T->rc); } } int main() { int n; BiTree *T; while(scanf("%d", &n) != EOF) { T = Creat(n); flag = 1; Show(T); printf("\n"); } return 0; }
相关文章推荐
- sdut 2128 树结构练习——排序二叉树(BST)的中序遍历
- 树结构练习——排序二叉树的中序遍历
- SDUTOJ 2128 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历 分类: 树 2015-06-21 11:05 12人阅读 评论(0) 收藏
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- SDUT 2128 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- OJ2128树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历
- 树结构练习——排序二叉树的中序遍历