Home » » Tinh So Nut O Do Cao h

Tinh So Nut O Do Cao h

Written By 1 on Thứ Hai, 14 tháng 5, 2012 | 09:58



#include "stdafx.h"
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef int element_type;
typedef struct node
{
  element_type element;
  struct node *left, *right;
} NODE;

NODE *root;

void khoi_tao_cay(NODE ** root)
{
  *root = NULL;
}

void insert(NODE *tmp, NODE **root)
{

  if (tmp->element < (*root)->element)
    if ((*root)->left)
      insert(tmp, &(*root)->left);
    else
       (*root)->left = tmp;
  else
    if ((*root)->right)
      insert(tmp, &(*root)->right);
    else
       (*root)->right = tmp;
}

void insert_node(element_type e, NODE **root)
{
   NODE *tmp;

   tmp = (NODE *)malloc(sizeof(NODE));
   tmp->element = e;
   tmp->left = NULL;
   tmp->right = NULL;
   if (*root == NULL)
     *root = tmp;
   else
     insert(tmp, root);
}

void nhap_cay(NODE **root)
{
  element_type e;
  printf("\n NHAP CAY NHI PHAN ! \n");
  printf("\n Nhap -1 de ket thuc !\n ");
  int i=1;
  do {

    printf("\n Nhap phan tu thu %d :",i);
    scanf("%d", &e);
    if (e != -1)
      insert_node(e, root);
 i++;
  } while (e != -1);
}

int  Count_All(NODE *root)  {  // Dem tong cac nut tren cay
        if (root == NULL)
return 0;
        return ( 1 +Count_All(root->left) + Count_All(root->right));
}

int Count_h(NODE *root, int h) //  Dem tong so nut o do cao h.
{
if(h>=0)
{
        if (root == NULL)
return 0;
        if (h == 0)
return 1;
else
return( Count_h(root->left, h-1) + Count_h(root->right, h-1));
}
else
return 0;

}

int Count_Up(NODE *root,int h)
{
int dem=0;
while(h>=0)
{
dem=dem + Count_h(root, h);
h=h-1;
}
return dem;
}

int Count_Down(NODE *root,int h)
{
return(Count_All(root) - Count_Up(root,h-1));
}


void main()
{
   khoi_tao_cay(&root);
   nhap_cay(&root);

   printf("\n So nut cua cay :%d",Count_All(root));
 
   int h;
   printf("\n Nhap mut de tinh so phan tu t :");
   scanf("%d",&h);  
   
    printf("\n \n Co %d nut o do cao %d  ",Count_h(root,h),h );

printf("\n \n Co % d tu do cao %d  ve goc  ",Count_Up(root,h),h );

printf("\n \n Co % d tu do cao %d ve den cuoi ",Count_Down(root,h),h );

   getch();
}

0 nhận xét:

Đăng nhận xét