前言
本文笔记包括树、二叉树的概念及代码(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;
}