二叉树遍历
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);
}