二叉树遍历
来源:互联网 发布:斗鱼主播都用什么软件 编辑:程序博客网 时间:2024/06/05 15:00
二叉树遍历
1.前序遍历规则:根左右;
2.中序遍历规则:左根右;
3.后序遍历规则:左右根;
4.按层遍历规则:从上到下,从左至右;
数据结构如下:
二叉树节点定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
1.二叉树节点个数
递归解法:
(1)如果二叉树为空,节点个数为0
(2)如果二叉树不为空,二叉树节点个数 = 左子树节点个数 + 右子树节点个数 + 1
参考代码如下:
int GetNodeNum(BinaryTreeNode * pRoot)
{
if(pRoot == NULL) // 递归出口
return 0;
return GetNodeNum(pRoot->m_pLeft) + GetNodeNum(pRoot->m_pRight) + 1;
}
2. 求二叉树的深度
递归解法:
(1)如果二叉树为空,二叉树的深度为0
(2)如果二叉树不为空,二叉树的深度 = max(左子树深度, 右子树深度) + 1
参考代码如下:
int GetDepth(BinaryTreeNode * pRoot)
{
if(pRoot == NULL) // 递归出口
return 0;
int depthLeft = GetDepth(pRoot->m_pLeft);
int depthRight = GetDepth(pRoot->m_pRight);
return depthLeft > depthRight ? (depthLeft + 1) : (depthRight + 1);
}
求
- 二叉树遍历、分层遍历
- 遍历二叉树--二叉树
- 【树】遍历二叉树
- 二叉树遍历
- 二叉树遍历
- 二叉树的遍历
- (原创)遍历二叉树
- 二叉树遍历-php
- 查找--遍历二叉树
- 遍历二叉树
- 二叉树遍历规则
- 二叉树的遍历
- 二叉树遍历
- 遍历二叉树
- 二叉树遍历问题
- 二叉树遍历
- 二叉树遍历(zz)
- 二叉树的遍历
- ios 文件上传
- 企业信息化的忌和记
- 2017年8月26日训练日记
- SUSE-11 本地 zypper 配置
- 论文笔记之Understanding and Diagnosing Visual Tracking Systems
- 二叉树遍历
- 重写(覆盖)和重载
- java LocalDate 为不可变对象
- C++模板实现单链表
- git 库中有库的问题
- DeepLearning_SparseAutoencoder
- selenium 小结
- 1017
- ArrayList