您的位置:首页 > 理论基础 > 数据结构算法

数据结构——树

2016-02-01 14:00 519 查看

一:二叉树

1.二叉树的建立和三种遍历
#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
char data;
struct node *left;
struct node *right;
}bitnode, *tree;

void create_tree(tree *t)//先序递归建立树
{                        //因为形参不改变实参,所以传递指向指针的指针
char ch;
scanf("%c", &ch);
while (getchar() != '\n')
continue;
if (ch == ' ')        //空格代表为空
*t = NULL;
else
{
*t = (bitnode*)malloc(sizeof(bitnode));
(*t)->data = ch; //有优先度的问题,->的优先度貌似大于*,所以加个括号
printf("Enter the left child\n");
create_tree(&(*t)->left); //要传递指向指针的指针
printf("Enter the right child\n");
create_tree(&(*t)->right);
}
}
void preorder(tree t)//先序遍历
{
if (t != NULL)
{
printf("%c ", t->data);
preorder(t->left);
preorder(t->right);
}
}
void inorder(tree t)//中序遍历
{
if (t != NULL)
{
inorder(t->left);
printf("%c ", t->data);
inorder(t->right);
}
}
void postorder(tree t)//后序遍历
{
if (t != NULL)
{
postorder(t->left);
postorder(t->right);
printf("%c ", t->data);
}
}

int main()
{
tree t;
create_tree(&t);
preorder(t);
printf("\n");
inorder(t);
printf("\n");
postorder(t);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: