#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
using namespace std;
typedef char ElemType;
FILE *fp;
void InitFile()
{
bool e;
fopen_s(&fp, "data.txt", "r");
//fopen_s(&fp, "tdata.txt", "w+");
if (!fp) exit(ERROR);
return;
}
typedef bool Status;
/******
file input:
abc00d00ef00g00
*******/
//二叉树的 链接式存储表示
typedef struct node
{
ElemType data;
struct node *lchild, *rchild;
}TreeNode, *tree_ptr;
Status CreateBitTree(tree_ptr &t)//创建一颗二叉树
{
char c;
//c = fgetchar();
fscanf_s(fp, "%c", &c);
printf("%c", c);
if (c == '0'){ t = NULL; return OK; }
else
{
t = (tree_ptr)malloc(sizeof(TreeNode));
if (!t) exit(ERROR);
t->data = c;
CreateBitTree(t->lchild);
CreateBitTree(t->rchild);
}
}
//用递归 中序遍历 二叉树
Status Inorder(tree_ptr t)
{
if (t)
{
Inorder(t->lchild);
printf("%c ", t->data);
Inorder(t->rchild);
}
return OK;
}
Status Preorder(tree_ptr t)
{
if (t)
{
printf("%c ", t->data);
Preorder(t->lchild);
Preorder(t->rchild);
}
return OK;
}
Status Postorder(tree_ptr t)
{
if (t)
{
Postorder(t->lchild);
Postorder(t->rchild);
printf("%c ", t->data);
}
return OK;
}
//by zhaoyang 2014.4.18
queue<tree_ptr> Q;
Status level_order(tree_ptr t)
{
Q.push(t);
while (!Q.empty())
{
tree_ptr c = Q.front();
Q.pop();
if (c)
{
printf("%c ", c->data);
Q.push(c->lchild);
Q.push(c->rchild);
}
}
return OK;
}
int main()
{
InitFile();
/*fp = fopen("data.txt", "r+");
if (!fp) exit(ERROR);*/
tree_ptr A;
CreateBitTree(A);
printf("\n先序遍历:\n");
Preorder(A);
printf("\n中序遍历:\n");
Inorder(A);
printf("\n后序遍历:\n");
Postorder(A);
printf("\n层序遍历\n");
level_order(A);
printf("\n");
return 0;
}
13.用二叉链表实现 二叉树的创建 遍历 4种
最新推荐文章于 2021-05-24 21:29:50 发布