当前位置:网站首页>二叉树详解
二叉树详解
2022-08-09 15:06:00 【R h yyy】
目录
引入树的概念

简单说下树的一些基本概念:
二叉树
概念


特殊的二叉树
1. 满二叉树:一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是满二叉
2. 完全二叉树:完全二叉树是效率很高的数据结构,完全二叉树是由满二叉树而引出来的。对

二叉树的一些重要性质
二叉树储存结构
顺序储存

链式储存

// 二叉链的创建
typedef int BTDataType;
structBinaryTreeNode
{
structBinTreeNode*Left; // 指向当前节点左孩子
structBinTreeNode*Right; // 指向当前节点右孩子
BTDataType_data; // 当前节点值域
}
// 三叉链的创建
structBinaryTreeNode
{
structBinTreeNode*Parent; // 指向当前节点的双亲
structBinTreeNode*Left; // 指向当前节点左孩子
structBinTreeNode*Right; // 指向当前节点右孩子
BTDataType_data; // 当前节点值域
};链式结构的实现



代码实现
前中后序的实现
// 二叉树的实现
typedef char TDataType;
typedef struct BTreeNode
{
struct BTreeNode*left;
struct BTreeNode*right;
TDataType data;
}BTNode;
//前序遍历
void PrevOrder(BTNode*root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
else
{
printf("%c ", root->data);
PrevOrder(root->left);
PrevOrder(root->right);
}
}
//中序遍历
void InOrder(BTNode*root)
{
if (root== NULL)
{
printf("NULL ");
return;
}
else
{
InOrder(root->left);
printf("%c ", root->data);
InOrder(root->right);
}
}
//后序遍历
void PostOrder(BTNode*root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
else
{
PostOrder(root->left);
PostOrder(root->right);
printf("%c ", root->data);
}
}计算二叉树节点个数
//分治算法
int BTreeSize(BTNode*root)
{
return root == NULL ? 0 : BTreeSize(root->left) + BTreeSize(root->right) + 1;
//节点个数=左子树节点个数+右子树节点个数+1,1是指该树根的节点
}计算叶子节点个数
//计算叶子数 分治算法
int BTreeLeafSize(BTNode*root)
{
if (root == NULL)
return 0;
if (root->left == NULL&&root->right == NULL) //若该树的没有左子树和右子树则就是叶子
return 1;
else //若有右子树或者右子树 则继续向下遍历访问
return BTreeLeafSize(root->left) + BTreeLeafSize(root->right);
}计算二叉树的最大深度
int maxDepth(struct TreeNode* root)
{
if(root==NULL)
{
return 0;
}
else
{
int leftdepth=maxDepth(root->left); //左子树的最大深度
int rightdepth=maxDepth(root->right); //右子树的最大深度
return leftdepth>rightdepth?leftdepth+1:rightdepth+1; //总的深度 = max(左子树深度,右子树深度)+ 1
}
}层序遍历
void BTreeLevelorder(BTNode*root)
{
Queue q; //使用队列实现层序遍历
QueueInit(&q);
if (root != NULL)
QueuePush(&q, root);
while (!QueueEmpty(&q))
{
BTNode*front = QueueFront(&q);
QueuePop(&q);
printf("%c ", front->data);
//上一层带出下一层
if (front->left != NULL)
QueuePush(&q, front->left);
if (front->right != NULL)
QueuePush(&q, front->right);
}
printf("\n");
}
边栏推荐
猜你喜欢
随机推荐
Base64工具类
js中的Date对象 及 将时间戳转换为yy-mm-dd hh:mm:ss格式的方法
MYSQL数据库一周基础入门(第二天)
Heap series_0x06: NT global flags and gflags.exe one page
第三章:GEE数据的使用(3.1-3.3)
Heap series_0x09: Example of heap corruption (illegal access + uninitialized + heap handle mismatch)
Go语言基础(十一):反射
位运算相关:2的幂、翻转图像、颠倒二进制位、N皇后II、比特位计数 ...
“泰迪杯”数据分析职业技能大赛B题 学生校园消费行为分析---复盘
Mysql学习(二)
文字样式的常见属性的如何使用?
选择器的使用
opacity和rgba的区别
Codeforces Round #808 (Div. 2)||沉淀
动态规划套题:零钱兑换、完全平方数
初始C语言(2) C生万物
5. Visualizing Geospatial Data
后代选择器和子代选择器
Nacos注册中心 Feign远程调用 Gateway服务网关
Access Characteristics of Constructor under Inheritance Relationship









