Data structure (ZKNUOJ) Count the number of nodes with degrees 0, 1 and 2 in a binary tree

Description

Given a preorder sequence, create a corresponding binary tree according to the sequence, and output the number of nodes with degrees 0, 1 and 2 of the binary tree.

Input

One line, the binary tree traverses the sequence in preorder, and the null pointer is occupied by the character ^

Output

One line, three integers represent the number of nodes with degrees

Sample Input

ABD ^^^ CE ^^ F ^^

Sample Output

3 1 2

Recursively traverse to find! ! ! ! ! !

#include<stdio.h>  
#include<stdlib.h>  
#include<string.h>  
typedef struct node{  
    char ch;  
    struct node *Lchild;  
    struct node *Rchild;  
}BiTNode,*BiTree;  
void Q_CreatTree(BiTree *T);  
int NodeNumber_1(BiTree T);
int NodeNumber_2(BiTree T);
int NodeNumber_0(BiTree T);
int main(void)  
{  
    BiTree T;
	Q_CreatTree(&T);
	getchar();
	printf("%d ",NodeNumber_0(T));//Node with degree 0
	printf("%d ",NodeNumber_1(T));//Node with degree 1
	printf("%d",NodeNumber_2(T));//Node with degree 2
}  
void Q_CreatTree(BiTree *T)//Preorder traversal to build a binary tree   
{  
    char str;  
    str=getchar();  
    if(str=='^')  
    {  
        *T=NULL;  
    }  
    else  
    {  
        (*T)=(BiTree)malloc(sizeof(BiTNode));  
        (*T)->ch=str;  
        Q_CreatTree( &( (*T)->Lchild ) );  
        Q_CreatTree( &( (*T)->Rchild ) );  
    }  
}
int NodeNumber_0(BiTree T)
{
	int i=0;
	if(T)
	{
		if(T->Lchild==NULL&&T->Rchild==NULL)
		{
			i=1;
		}
		else
		{
			i=NodeNumber_0( T->Lchild ) + NodeNumber_0( T->Rchild );
		}
	}
	return i;
}
int NodeNumber_1(BiTree T)
{
	int i=0;
	if(T)
	{
		if( (T->Lchild==NULL&&T->Rchild!=NULL) ||(T->Lchild!=NULL&&T->Rchild==NULL))
		{
			i=1+NodeNumber_1(T->Lchild)+NodeNumber_1(T->Rchild);
		}
		else
		{
			i=NodeNumber_1(T->Lchild)+NodeNumber_1(T->Rchild);
		}
	}
	return i;
}
int NodeNumber_2(BiTree T)
{
	int i=0;
	if(T)
	{
		if((T->Lchild!=NULL)&&(T->Rchild!=NULL))
		{
			i=1+NodeNumber_2(T->Lchild) + NodeNumber_2(T->Rchild);
		}
		else
		{
			i= NodeNumber_2(T->Lchild) + NodeNumber_2(T->Rchild);
		}
	}
	return i;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325446651&siteId=291194637