【无标题】

C语言 统计二叉树叶子结点,度为2的结点、所有结点个数(递归)

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
	int data;
	struct node* left;
	struct node* right;
}Node;
void insertlist(Node* T, int x)
{
	Node* temp;
	temp = malloc(sizeof(Node));
	temp->data = x;
	temp->left = NULL;
	temp->right = NULL;

	Node* p;
	p = malloc(sizeof(Node));
	p = T;
	while (p)
	{
		if (p->data > x)
		{
			if (p->left == NULL)
			{
				p->left = temp;
				return;
			}
			else
			{
				p = p->left;
			}
		}
		else
		{
			if (p->right == NULL)
			{
				p->right = temp;
				return;
			}
			else
			{
				p = p->right;
			}
		}
	}
}
void  preorder(Node* T)
{
	Node* p;
	p = malloc(sizeof(Node));
	p = T;
	if (p)
	{
		printf("%d ", p->data);
		preorder(p->left);
		preorder(p->right);
	}
}
void  inorder(Node* T)
{
	Node* p;
	p = malloc(sizeof(Node));
	p = T;
	if (p)
	{

		inorder(p->left);
		printf("%d ", p->data);
		inorder(p->right);
	}
}
void  postorder(Node* T)
{
	Node* p;
	p = malloc(sizeof(Node));
	p = T;
	if (p)
	{

		postorder(p->left);

		postorder(p->right);
		printf("%d ", p->data);
	}
}
int CountLeafNode(Node* T)
{
	Node* p;
	p = malloc(sizeof(Node));
	p = T;
	if (p == NULL)
	{
		return 0;
	}
	if (p->left == NULL && p->right == NULL)
	{
		return 1;
	}
	else
	{
		return CountLeafNode(p->left) + CountLeafNode(p->right);
	}
}
int CountTwoNode(Node* T)
{
	Node* p;
	p = malloc(sizeof(Node));
	p = T;
	int count = 0;
	if (p == NULL)
	{
		return 0;
	}
	else if (p->left && p->right)
	{
		return CountTwoNode(p->left) + CountTwoNode(p->right) + 1;
	}
	else
	{
		return CountTwoNode(p->left) + CountTwoNode(p->right);
	}
}
int CountNode(Node* T)
{
	Node* p;
	p = malloc(sizeof(Node));
	p = T;

	if (p == NULL)
	{
		return 0;
	}
	else
	{
		return CountNode(p->left) + CountNode(p->right) + 1;
	}
}
int main()
{
	int arr[10] = { 5,2,7,1,3,4,6,8,9,10 };
	Node* T;
	T = malloc(sizeof(Node));
	T->data = arr[0];
	T->left = NULL;
	T->right = NULL;

	for (int i = 1; i < 10; i++)
	{
		insertlist(T, arr[i]);
	}

	preorder(T);
	printf("\n");
	inorder(T);
	printf("\n");
	postorder(T);
	printf("\n");

	int count = 0;
	count = CountLeafNode(T);
	printf("the number of leaf node: %d \n", count);
	int count2 = 0;
	count2 = CountTwoNode(T);
	printf("the number of two node: %d \n", count2);

	int count3 = 0;
	count3 = CountNode(T);
	printf("the number of all node: %d ", count3);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值