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

数据结构和算法--二叉树创建和递归遍历

2016-11-09 21:16 561 查看
//完全二叉树的创建以及遍历(递归)

#include <stdio.h>
#include <stdlib.h>

//定义数据类型
typedef int datatype_t;

//定义结构体
typedef struct node{
datatype_t data;
struct node *lchild;
struct node *rchild;
}bitree_t;

//创建一个二叉树(n表示结点总数,i表示根结点)
bitree_t *bitree_create(int n, datatype_t i)
{
bitree_t *bt;
bt = (bitree_t *)malloc(sizeof(bitree_t));
bt->data = i;

if(2 * i <= n)
{
bt->lchild = bitree_create(n, 2 * i);
}
else
{
bt->lchild = NULL;
}

if(2 * i + 1 <= n)
{
bt->rchild = bitree_create(n, 2 * i + 1);
}
else
{
bt->rchild = NULL;
}

return bt;
}

//先序遍历
int bitree_before_order(bitree_t *root)
{
if(root == NULL)
{
return 0;
}

printf("%d ", root->data);

if(root->lchild != NULL)
{
bitree_before_order(root->lchild);
}

if(root->rchild != NULL)
{
bitree_before_order(root->rchild);
}

return 0;
}

//中序遍历
int bitree_in_order(bitree_t *root)
{
if(root == NULL)
{
return 0;
}

if(root->lchild != NULL)
{
bitree_in_order(root->lchild);
}

printf("%d ", root->data);

if(root->rchild != NULL)
{
bitree_in_order(root->rchild);
}

return 0;
}

//后序遍历
int bitree_after_order(bitree_t *root)
{
if(root == NULL)
{
return 0;
}

if(root->lchild != NULL)
{
bitree_after_order(root->lchild);
}

if(root->rchild != NULL)
{
bitree_after_order(root->rchild);
}

printf("%d ", root->data);

return 0;
}

int main(int argc, const char *argv[])
{
bitree_t *root;
root = bitree_create(8, 1);

bitree_before_order(root);
putchar(10);

bitree_in_order(root);
putchar(10);

bitree_after_order(root);
putchar(10);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息