二叉树与递归

二叉树的三种遍历方法:
前序遍历:根结点 —> 左子树 —> 右子树

中序遍历:左子树—> 根结点 —> 右子树

后序遍历:左子树 —> 右子树 —> 根结点

下面是三种遍历的代码和计算树的大小,计算叶子的个数,树的高度和计算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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值