关于二叉树,在数据结构 【树 和 二叉树】-优快云博客这篇文章已经讲到了一些概念。这篇文章主要讲讲关于二叉树的遍历以及关于递归的一些实际问题。
在正式探讨二叉树之前,我们快速构建一个简单的二叉树,方便我们后续的操作。我们按照下图的连接方式构造一棵简单的二叉树。
typedef int BTDataType;
typedef struct BinaryTreeNode
{
BTDataType data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
BTNode* BuyNode(BTDataType x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
if (node == NULL)
{
perror("malloc fail");
return NULL;
}
node->data = x;
node->left = NULL;
node->right = NULL;
}
BTNode* creatTree()
{
BTNode* node1 = BuyNode(1);
BTNode* node2 = BuyNode(2);
BTNode* node3 = BuyNode(3);
BTNode* node4 = BuyNode(4);
BTNode* node5 = BuyNode(5);
BTNode* node6 = BuyNode(6);
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
return node1;
}
1、二叉树的遍历
所谓二叉树的遍历就是二叉树按照某种特定的规则,依次对二叉树中的节点进行相应的操作,并且每个节点只能操作一次。按照访问的顺序规则,二叉树有前序、中序、以及后序遍历。
注意:建议这里将每一个节点看成由根和自己的左右子树构成。下面列出各访问方式的顺序
- 前序遍历: 根 左子树 右子树
- 中序遍历: 左子树 根 右子树
- 后序遍历: 左子树 右子树 根
我们可以看到所谓的访问顺序都是根据根的顺序来决定的。 二叉树的遍历主要是使用递归的方式来进行实现的;
//前序遍历
void pre_order(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
printf("%d ", root->data);//根
pre_order(root->left);//左子树
pre_order(root->right);//右子树
}
//中序遍历
void in_order(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
in_order(root->left);//左子树
printf("%d ", root->data);//根
in_order(root->right);//右子树
}
//后序遍历
void post_order(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
post_order(root->left);//左子树
post_order(root->right);//右子树
printf("%d ", root->data);//根
}
2、节点个数
二叉树节点的个数也是通过递归的方式来获取的。主要思路:
节点的总个数 = 左子树的节点个数 + 右子树的节点个数 + 1
//树的节点数 = 左右子树节点个数 + 1
int tree_size(BTNode* root)
{
if (root == NULL)
{
return 0;
}
int left = tree_size(root->left);
int right = tree_size(root->right);
return left + right + 1;
}
3、树的高度
树的高度 = 左右子树中最高的高度 + 1
//树的高度= 左右子树高度大的 + 1
int tree_height(BTNode* root)
{
if (root == NULL)
{
return 0;
}
int left_height = tree_height(root->left);
int right_height = tree_height(root->right);
int max = left_height > right_height ? left_height : right_height;
return max + 1;
}
4、树的第K层节点的个数
第K层节点的个数 = 左子树的第K-1层 + 右子树的第K-1层
假设求根节点的第三层有多少个节点,那么当k递减到1时就应该停止递归并返回1;
//根的第K层 = 左子树的第k-1层 + 右子树的第k-1层
int tree_k_level(BTNode* root, int k)
{
if (root == NULL)
{
return 0;
}
if (k == 1)
{
return 1;
}
int left_num = tree_k_level(root->left, k - 1);
int right_num = tree_k_level(root->right, k - 1);
return left_num + right_num;
}