绪论
二叉树是一种树形结构,其中每个节点最多有两个子节点,称左子节点与右子节点。每个节点最多有一个父节点,根节点0个
二叉树分为二叉搜索树,完全二叉树,平衡二叉树,红黑树等,
二叉树的建立可以有辅助队列法和递归法,二者各有优缺点
这里采用递归法
1.二叉树的创建
#include<stdlib.h>
#include<stdio.h>
typedef struct node
{
int data;
struct node *lchild;
struct node *rchild;
}bintree;
bintree* creat_bintree(int root, int n)
{
bintree* r = malloc(sizeof(bintree));
if (r == NULL)
{
perror("malloc");
return 0;
}
r->data = root;
printf("root=%d\n", root);
if (root<<1<=n)
{
r->lchild = creat_bintree(root<<1, n);
}
else
r->lchild = NULL;
if ((1 + (root<<1))<=n)
{
r->rchild = creat_bintree((root<<1)+1, n);
}
else
r->rchild = NULL;
}
root<<1,是乘2的意思。
为什么这么判断,这是因为在二叉树中若第i个节点存在,若存在左子树,与右子树,则左子树序号为,右子树的序号为
2.二叉树的遍历
2.1.前序遍历
前序遍历的顺序为根节点,左节点,右节点
int liftr(bintree* b)
{
if( b == NULL)
{
return 0;
}
//先访问根节点
printf("%d\n", b->data);
//再访问左节点
liftr(b->lchild);
//最后访问右节点
liftr(b->rchild);
return 0;
}
2.2.中序遍历
中序遍历顺序为左节点,根节点,右节点。
int rigtr(bintree* b)
{
if( b == NULL)
{
return 0;
}
//先访问左节点
liftr(b->lchild);
//再访问根节点
printf("%d\n", b->data);
//最后访问右节点
liftr(b->rchild);
return 0;
}
2.3.后序遍历
后序遍历顺序为左节点,右节点, 根节点
int endtr(bintree* b)
{
if( b == NULL)
{
return 0;
}
//先访问左节点
liftr(b->lchild);
//再访问右节点
liftr(b->rchild);
//最后访问根节点
printf("%d\n", b->data);
return 0;
}