- 二叉树(Binary tree)是树形结构的一个重要类型。许多实际问题抽象出来的数据结构往往是二叉树形式,即使是一般的树也能简单地转换为二叉树,而且二叉树的存储结构及其算法都较为简单,因此二叉树显得特别重要。二叉树特点是每个节点最多只能有两棵子树,且有左右之分
- 二叉树(binary tree)是指树中节点的度不大于2的有序树,它是一种最简单且最重要的树。二叉树的递归定义为:二叉树是一棵空树,或者是一棵由一个根节点和两棵互不相交的,分别称作根的左子树和右子树组成的非空树;左子树和右子树又同样都是二叉树
以下是二叉树的增删改查
head.h
#ifndef __TREE_H__
#define __TREE_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef char datadef[10];
typedef struct Node // 二叉树结点(严格有序)
{
datadef data;
struct Node *lchild; // 左孩子
struct Node *rchild; // 右孩子
} *tree, Tree;
tree creat(); // 创建树结点
int f_output(tree T); // 先序遍历
int m_output(tree T); // 中序遍历
int r_output(tree T); // 后序遍历
int h_tree(tree T); // 深度计算
void count(tree T, int *n0, int *n1, int *n2); // 结点计算
void free_T(tree T); // 释放
#endif
fun.c
#include “head.h”
tree creat() // 创建树结点
{
tree T = (tree)malloc(sizeof(Tree));
if (T == NULL)
{
return NULL;
}
datadef s;
printf("你要输入的元素是(#为空):");
scanf("%s", s);
if (strcmp(s, "#") == 0)
{
return NULL;
}
strcpy(T->data, s);
puts("");
printf("\t%s\t的左孩子\n", T->data);
T->lchild = creat();
puts("");
printf("\t%s\t的右孩子\n", T->data);
T->rchild = creat();
return T;
}
int f_output(tree T) // 先序遍历
{
static int n = 0;
if (T)
{
printf("%s\t", T->data);
n++;
f_output(T->lchild);
f_output(T->rchild);
return n;
}
}
int m_output(tree T) // 中序遍历
{
static int n = 0;
if (T)
{
m_output(T->lchild);
printf("%s\t", T->data);
n++;
m_output(T->rchild);
return n;
}
}
int r_output(tree T) // 后序遍历
{
static int n = 0;
if (T)
{
r_output(T->lchild);
r_output(T->rchild);
printf("%s\t", T->data);
n++;
return n;
}
}
int h_tree(tree T) // 深度计算
{
if (T == NULL)
{
return 0;
}
static int high = 1;
high = h_tree(T->lchild) > h_tree(T->rchild) ? h_tree(T->lchild) + 1 : h_tree(T->rchild) + 1;
return high;
}
void count(tree T, int *n0, int *n1, int *n2) // 结点计算
{
if (T == NULL)
{
return;
}
count(T->lchild, n0, n1, n2);
count(T->rchild, n0, n1, n2);
if (T->lchild == NULL && T->rchild == NULL)
{
(*n0)++;
}
else if (T->lchild != NULL && T->rchild != NULL)
{
(*n2)++;
}
else
{
(*n1)++;
}
}
void free_T(tree T) // 释放
{
if (!T)
{
return;
}
free_T(T->lchild);
free_T(T->rchild);
free(T);
T = NULL;
}
main.c
#include "head.h"
int main(int argc, const char *argv)
{
tree T = creat(); // 创建二叉树
int n;
puts("");
printf("先序遍历:");
n = f_output(T); // 先序遍历
printf("该二叉树有%d个结点\n", n);
puts("");
printf("中序遍历:");
n = m_output(T); // 中序遍历
printf("该二叉树有%d个结点\n", n);
puts("");
printf("后序遍历:");
n = r_output(T); // 后序遍历
printf("该二叉树有%d个结点\n", n);
puts("");
int h;
printf("树的高度为:%d\n", h_tree(T)); // 深度计算
int n0 = 0, n1 = 0, n2 = 0;
count(T, &n0, &n1, &n2);
printf("叶子结点有:%d\n", n0);
printf("度为1的结点有:%d\n", n1);
printf("度为2的结点有:%d\n", n2);
free_T(T); // 释放
}