Linux C 数据结构—树
一.树概述
树(Tree)是n(n≥0)个节点的有限集合T,它满足两个条件 :
有且仅有一个特定的称为根(Root)的节点;
其余的节点可以分为m(m≥0)个互不相交的有限集合T1、T2、……、Tm,其中每一个集合又是一棵树,并称为其根的子树(Subtree)。
树、子树、森林。
父节点、子节点、兄弟节点、堂兄弟节点、叶节点(度数为0的子节点)
根节点:没有前驱节点
叶节点:没有后继节点
度: 一个节点的子树的个数称为该节点的度数,一棵树的度数是指该树中节点的最大度数。
路径: 从根到当前节点路过(纵向)的边数。
深度: 也叫高度。 从根开始数,根的位置深度为1. 向下数分别是 1、 2、 3、 4…
二叉树: 严格区分左孩子和右孩子
满二叉树: 深度为k(k≥1)时有2k-1个节点的二叉树。
完全二叉树 :只有最下面两层有度数小于2的节点,且最下面一层的叶节点集中在最左边的若干位置上。
!!!二叉树的遍历(重点掌握):
-
已知二叉树,可以按各种规则遍历
先序遍历: 根 --> 左 --> 右
中序遍历: 左 --> 根 --> 右
后序遍历: 左 --> 右 --> 根 -
根据遍历的节点顺序,可以还原二叉树的模样。
先序: A B C E H F I J D G K
中序: A H E C I F J B D K G
口诀: 先序后序分前后,中序分左右。 -
树的存储:
顺序存储: 数组。
链式存储: 节点。
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}bittree_t;
二.示例代码:链式存储
#include <stdio.h>
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}bittree_t;
//先序遍历
void first_order(bittree_t *t)
{
if(t != NULL)
{
printf("%6c",t->data);
first_order(t->lchild);
first_order(t->rchild);
}
return ;
}
//中序遍历
void mid_order(bittree_t *t)
{
if(t != NULL)
{
mid_order(t->lchild);
printf("%6c",t->data);
mid_order(t->rchild);
}
return ;
}
//后序遍历
void last_order(bittree_t *t)
{
if(t != NULL)
{
last_order(t->lchild);
last_order(t->rchild);
printf("%6c",t->data);
}
return ;
}
int main()
{
bittree_t A = {'A',NULL,NULL};
bittree_t B = {'B',NULL,NULL};
bittree_t C = {'C',NULL,NULL};
bittree_t D = {'D',NULL,NULL};
bittree_t E = {'E',NULL,NULL};
bittree_t F = {'F',NULL,NULL};
A.lchild = &B;
A.rchild = &C;
B.rchild = &D;
C.lchild = &E;
E.rchild = &F;
printf("first: ");
first_order(&A);
printf("\n");
printf("middle: ");
mid_order(&A);
printf("\n");
printf("last: ");
last_order(&A);
printf("\n");
return 0;
}