目录
一、树
1.度(结点的分类):
结点拥有的子树的数量是为树的度。
2.树的层&深度:
如图所示,结点的层次从根算起,根为第一层,根的孩子为第二层以此类推。
一棵树的深度是树中结点层次最大的值称为树的深度,或高度。
3.二叉树
完全二叉树:只有最下面两层不满,如果只有一个节点,节点为左孩子(满 二叉树摘掉几片叶子)
满二叉树:若深度为K,节点个数为2k-1
个数已知,求深度:k=log2(N)+1
4.二叉树的存储
(1)数组存储:补全为满二叉树
(2)链式存储;
5.二叉树的遍历
每个节点访问且访问一次
遍历方法:
- 先序:根左右 A-B-C-D-E-F-G-H-K
- 中序:左根右 B-D-C-A-E-H-G-K-F
- 后序:左右根 D-C-B-H-K-G-F-E-A
面试题:已知先序:ABCDEFGH ,中序:BDCEAFHG,画出二叉树
分析:
根据先序给出的信息可以得到A为根,再根据中序可知根左边为BDCE,右边为FHG。先序遍历B是先出现的,所以B为根。
在中序遍历中B的左边为空,所以DCE是B的右子树。先序C是先出现,即根,中序遍历D在C前面,E在后面,所以C的左子树为D,右子树为E,至此,左子树完。
右子树中,F在先序中最先出现为根,FG都在F的右边,在先序中又因为G先出现,所以G为根,中序中H在G的前面,所以H为G的左子树。
6.哈夫曼树
二、图
有向图:边是有方向的
无向图:边是无方向的
节点:存放数据
节点的度:某个节点和几个其它节点相连,就是该节点有几条边
边:节点之间的连线
权: 指边的长度
邻接点:两个点直接相连 路径:一个节点到另一个所经历的所有节点的集合
1.图的存储
(1)顺序存储,使用二维矩阵存储
(2)链式存储
以这个为例,表示从0节点分别与1、2、3节点联通,权值分别为2、4、6.
2.图的遍历
(1)深度遍历:
从顶点出发,任意走做好标记,走不通按原路返回。
(2)广度遍历:
一层一层遍历
三、栈
一种先进后出的线性结构,只允许在一端进行操作的线性表,如电梯,弹夹,水杯。
1.顺序栈:使用数组来实现栈
出栈判空,入栈判满
实现代码:
#include <stdio.h>
#define N 8
struct seq_stack{
int arr[N];
int pos;
};
struct seq_stack stack;
void stack_init(struct seq_stack *pstack)//栈的初始化
{
pstack->pos = 0;
}
int stack_is_empty(struct seq_stack *pstack)//判空
{
return pstack->pos==0 ? 1: 0;
}
int stack_is_full(struct seq_stack *pstack)//判满
{
return pstack->pos == N ? 1:0;
}
int stack_push(struct seq_stack *pstack, int val)//入栈
{
if( stack_is_full(pstack) ){ //如果栈也满,则退出
return -1;
}
pstack->arr[ pstack->pos ] = val;
pstack->pos++;
return 0;
}
int stack_pop(struct seq_stack *pstack, int *val)//出栈
{
if(stack_is_empty(pstack)){ //如果栈为空,退出
return -1;
}
pstack->pos--;
*val = pstack->arr [ pstack->pos ] ;
return 0;
}
int stack_cnt(struct seq_stack *pstack)
{
return pstack->pos;
}
int main(void)
{
stack_init(&stack);
for(int i=11;i<=99;i+=11){
int ret = stack_push(&stack, i);
if(ret <0 ){
printf("push %d failed\n",i);
}
}
for(int i=1;i<=9;i++){
int val;
int ret = stack_pop(&stack, &val);
if(ret<0){
printf("pop failed\n");
return 0;
}else {
printf("%d ",val);
}
}
}
2.链式栈:使用链表来实现栈
实现代码:
#include "stdio.h"
#include "stdlib.h"
struct node {
int val;
struct node *next;
};
struct node head;
struct node *pthead=&head;
void stack_init(struct node *pthead)//栈的初始化
{
pthead->next =NULL;
}
void stack_push(struct node *pthead, int val)//入栈
{
struct node *p = malloc(sizeof(*p));
p->val = val; p->next = NULL;
p->next = pthead->next;
pthead->next=p;
}
int stack_pop(struct node *pthead, int *val)//出栈
{
if(pthead->next == NULL){
return -1;
}
struct node *p = pthead->next;
pthead->next=p->next;
*val = p->val;
free(p);
return 0;
}
int main()
{
for(int i=11;i<=99;i+=11){
stack_push(pthead,i);
}
for(int i=1;i<=10;i++){
int val;
int ret = stack_pop(pthead,&val);
if(ret<0){
printf("pop ffailed\n");
return -34;
}else {
printf("%d ",val);
}
}
return 0;
}