数据结构(树)

前言

        本文笔记包括树、二叉树的概念及代码(5个操作)。

        树是n(n≥0)个结点的有限集合,有且仅有一个特定的根结点,其余结点可以分为m(m≥0)个互不相交的有限集合,其中每一个集合又是一棵树,并称为其根的子树。

  • 度数:一个结点子结点的个数;
  • 树的度数:结点度数最大的那个;
  • 叶子结点:度数为0的结点;
  • 结点层次:根结点所在层次为1,根的子结点所在层次为2,。。。
  • 树的高度和深度:结点层次最大的

二叉树(Binary Tree)

        二叉树是n(n≥0)个结点的有限集合,空集或者有一个结点以及两棵互不相交的,分别称为左子树和右子树的二叉树组成。最大度数为2,严格区分左右孩子。

特性

        (1)一颗深度为k的二叉树,在第k层上节点个数最多 2^(k-1) 
        (2)一颗深度为k的二叉树,节点个数最多为 2^k - 1
        (3)任意一颗二叉树度数为0的节点个数都比都是为2的节点个数多1个
                即 n0 = n2 +1
        二叉树的结点数等于度数为0,度数为1,度数为2节点数的和
                n = n0+n1+n2

二叉树遍历

前序遍历(per_orde)          根左右
中序遍历(in_order)           左根右
后序遍历(post_order)       左右根

代码

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
	char data;
	struct node* lchild;
	struct node* rchild;
}tree_t;
tree_t* create()
{
	char ch;
	scanf("%c",&ch);
	if('#' == ch)
		return NULL;
	tree_t* root = (tree_t*)malloc(sizeof(tree_t));
	if(NULL == root)
	{
		printf("root malloc failed\n");
		return NULL;
	}
	root->data = ch;
	root->lchild = create();
	root->rchild = create();
	return root;
}

//前序遍历
void per_order(tree_t *root)
{
	if(root == NULL)
		return;
	printf("%c ",root->data);
	per_order(root->lchild);
	per_order(root->rchild);
}
//中序遍历
void in_order(tree_t* root)
{
	if(root == NULL)
		return;
	per_order(root->lchild);
	printf("%c ",root->data);
	per_order(root->rchild);
}
//后序遍历
void post_order(tree_t* root)
{
	if(root == NULL)
		return;
	per_order(root->lchild);
	per_order(root->rchild);
	printf("%c ",root->data);

}
//摧毁二叉树(删除二叉树)
void clear(tree_t* root)
{
	//递归结束条件
	if(root == NULL)
		return ;
	clear(root->lchild);
	clear(root->rchild);
	printf("%c ",root->data);//先打印的谁,就是释放的谁
	free(root);//释放根
}
int main()
{
	tree_t* root = create();

	printf("前序:");
	per_order(root);
	printf("\n中序:");
	in_order(root);
	printf("\n后序:");
	post_order(root);
	printf("\n");
	clear(root);
	return 0;
}

霍夫曼树

        霍夫曼编码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值