软基作业:二叉树的创建与遍历
2013-10-30 14:11
246 查看
题目要求:
ex4_1:
程序如下:
运行结果如下:
ex4_1:
1)二叉树结点类型定义为: typedefstructbnode { intdata; structbnode*lc,*rc; }bnode_type; 2)编写中序遍历函数; 3)编写后序遍历函数; 4)编写先序遍历函数; 5)编写create函数建立二叉排序树; 6)编写main()函数,先调用create函数,建立一颗二叉排序树;然后分别调用中序、后序、先序遍历函数,将二叉树的先序、中序和后序遍历序列输出到屏幕上。
程序如下:
#include <stdio.h> #include <stdlib.h> typedef struct bnode { int data; struct bnode *lc, *rc; }bnode_type; bnode_type *create(void); void preorder(bnode_type *root); void inorder(bnode_type *root); void postorder(bnode_type *root); int main(void) { bnode_type *tree; printf("Please input your datas(ended by -1):"); tree = create(); printf("Preorder:\n"); preorder(tree); printf("\nInorder:\n"); inorder(tree); printf("\nPostorder:\n"); postorder(tree); printf("\n"); return 0; } bnode_type *create(void) { int data; bnode_type *node, *root, *newnode; root = (bnode_type *)malloc(sizeof(bnode_type)); if (root == NULL) { printf("Memorty Error!\n"); exit(EXIT_FAILURE); } root->data = -1; root->lc = root->rc = NULL; scanf("%d", &data); while (data != -1) { if (root->data == -1) { root->data = data; scanf("%d", &data); continue; } else { node = root; for (;;) { if (data < node->data) { if (node->lc == NULL) { newnode = (bnode_type *)malloc(sizeof(bnode_type)); if (newnode == NULL) { printf("Memory Error!\n"); exit(EXIT_FAILURE); } newnode->data = data; newnode->lc = newnode->rc = NULL; node->lc = newnode; break; } else node = node->lc; } else { if (node->rc == NULL) { newnode = (bnode_type *)malloc(sizeof(bnode_type)); if (newnode == NULL) { printf("Memory Error!\n"); exit(EXIT_FAILURE); } newnode->data = data; newnode->lc = newnode->rc = NULL; node->rc = newnode; break; } else node = node->rc; } } } scanf("%d", &data); } return root; } void preorder(bnode_type *root) { if (root == NULL || root->data == -1) return ; printf("%d\t", root->data); if (root->lc != NULL) preorder(root->lc); if (root->rc != NULL) preorder(root->rc); } void inorder(bnode_type *root) { if (root == NULL || root->data == -1) return ; if (root->lc != NULL) inorder(root->lc); printf("%d\t", root->data); if (root->rc != NULL) inorder(root->rc); } void postorder(bnode_type *root) { if (root == NULL || root->data == -1) return ; if (root->lc != NULL) postorder(root->lc); if (root->rc != NULL) postorder(root->rc); printf("%d\t", root->data); }
运行结果如下:
相关文章推荐
- 先根遍历创建二叉树
- 从前序遍历数组创建二叉树 c实现
- 二叉树的先序创建,先序,中序,后序的递归与非递归遍历,层次遍历,叶子结点数及树的深度
- 二叉树创建及遍历算法(递归及非递归)
- 二叉树的创建、前序遍历、中序遍历、后序遍历
- 二叉树创建以及遍历方式
- 二叉树的创建、遍历
- C,C++创建二叉树,以及3种遍历
- 二叉树:树的创建和遍历
- 二叉树 1.0 -- 创建二叉树、遍历二叉树、二叉树常见问题求解
- 先序顺序输入结点值创建二叉树,并按先序,中序和后序遍历输出
- 二叉树的创建与遍历
- 创建、前序、中序、后序递归遍历二叉树
- 【二叉树】二叉树的创建、遍历、销毁、求树的最大深度
- 二叉树的创建和递归遍历
- 程序员面试100题(算法)之层次遍历二叉树(含二叉树前序创建、层次遍历、前序遍历)
- java创建二叉树及遍历
- java二叉树的创建,遍历及其他方法
- 二叉树——创建,递归遍历输出
- 数据结构——二叉树的创建和遍历