二叉树的三种遍历方法:
前序遍历:根结点 —> 左子树 —> 右子树
中序遍历:左子树—> 根结点 —> 右子树
后序遍历:左子树 —> 右子树 —> 根结点
下面是三种遍历的代码和计算树的大小,计算叶子的个数,树的高度和计算k层结点的个数,都是递归思想
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int BTDatatype;
typedef struct BinaryTreeNode {
BTDatatype data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
BTNode* CreatNode(BTDatatype x)//创建树的结点
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
assert(node);
node->data = x;
node->left = NULL;
node->right = NULL;
return node;
}
BTNode* CreatTree()//手动创建一个树
{
BTNode* node1 = CreatNode(1);
BTNode* node2 = CreatNode(2);
BTNode* node3 = CreatNode(3);
BTNode* node4 = CreatNode(4);
BTNode* node5 = CreatNode(5);
BTNode* node6 = CreatNode(6);
BTNode* node7 = CreatNode(7);
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
node5->right = node7;
return node1;
}
void PrevOrder(BTNode* root)//前序遍历
{
if (root == NULL)
{
printf("N ");
return;
}
printf("%d ", root->data);
PrevOrder(root->left);
PrevOrder(root->right);
}
void INOrder(BTNode* root)//中序遍历
{
if (root == NULL)
{
printf("N ");
return;
}
INOrder(root->left);
printf("%d ", root->data);
INOrder(root->right);
}
void TailOrder(BTNode* root)//后序遍历
{
if (root == NULL)
{
printf("N ");
return;
}
TailOrder(root->left);
TailOrder(root->right);
printf("%d ", root->data);
}
int TreeSize(BTNode* root)//树的大小
{
return (root == NULL) ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
int TreeLeafSize(BTNode* root)//叶子的个数
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
return TreeLeafSize(root->left) + TreeLeafSize(root->right);
}
int TreeHigh(BTNode* root)//树的高度
{
if (root == NULL)
return 0;
int LeftHigh = TreeHigh(root->left);
int RightHigh = TreeHigh(root->right);
return LeftHigh > RightHigh ? LeftHigh + 1 : RightHigh + 1;
}
int numk(BTNode* root, int k)//计算k层结点的个数
{
assert(k > 0);
if (root == NULL)return 0;
if (k == 1)
{
return 1;
}
return numk(root->left, k - 1) + numk(root->right, k - 1);
}
int main()
{
BTNode* root = CreatTree();
printf("前序遍历:");
PrevOrder(root);
printf("\n");
printf("中序遍历:");
INOrder(root);
printf("\n");
printf("后序遍历:");
TailOrder(root);
printf("\n");
printf("树的大小:");
printf("%d", TreeSize(root));
printf("\n");
printf("叶子的个数:");
printf("%d", TreeLeafSize(root));
printf("\n");
printf("树的高度:");
printf("%d", TreeHigh(root));
printf("\n");
int k = 0;
scanf("%d", &k);
printf("第%d层的结点个数为:", k);
printf("%d", numk(root, k));
printf("\n");
return 0;
}