学习导航
一、三种遍历方式
1.前序遍历
2.中序遍历
3.后序遍历
二、有关二叉树的基本问题
1.求结点个数
【形式①:使用全局变量】
int cnt = 0;
void BinaryTreeSize(BTNode* root)
{
if (root == NULL)
return;
cnt++;
BinaryTreeSize(root->left);
BinaryTreeSize(root->right);
}
【形式②:采用传址调用】
void BinaryTreeSize(BTNode* root , int* cnt)
{
if (root == NULL)
return;
++(*cnt);
BinaryTreeSize(root->left, cnt );
BinaryTreeSize(root->right, cnt);
}
【形式③:分治的思想】
int BinaryTreeSize(BTNode* root)
{
return root == NULL ? 0 : BinaryTreeSize(root->left) +
BinaryTreeSize(root->right) + 1;
}
2.求叶子结点个数
【形式①:遍历+计数】
void BinaryTreeLeafSize(BTNode* root)
{
if (root == NULL)
return;
if (!root->left && !root->right)
{
cnt++;
return;
}
BinaryTreeLeafSize(root->left);
BinaryTreeLeafSize(root->right);
}
【形式②:分治思想】
int BinaryTreeLeafSize(BTNode* root)
{
if (root == NULL)
return 0;
if (!root->left && !root->right)
{
return 1;
}
return BinaryTreeLeafSize(root->left)
+ BinaryTreeLeafSize(root->right);
}
3.求第k层的结点个数
int BinaryTreeLevelKSize(BTNode* root, int k)
{
if (root == NULL)
return 0;
if (k == 1)
return 1;
return BinaryTreeLevelKSize(root->left, k - 1)
+ BinaryTreeLevelKSize(root->right, k - 1);
}
4.求二叉树的深度
int BinaryTreeDepth(BTNode* root)
{
if (root == NULL)
return 0;
int leftdepth = BinaryTreeDepth(root->left);
int rightdepth = BinaryTreeDepth(root->right);
return leftdepth < rightdepth ? rightdepth + 1 : leftdepth + 1;
}