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;
}