#include "stdafx.h"
#include <stdio.h>
#include<conio.h>
struct Node
{
    Node* pLeft;
    Node* pRight;
    int iX;
};
typedef Node* Tree;
Node* TaoNode(int X)
{
    Node* p = new Node;
    if (p == NULL)
        return NULL;
    p->pLeft = NULL;
    p->pRight = NULL;
    p->iX=X;
    return p;
}
void ThemNodeVaoCay(Node* p, Tree &c)
{
    if (c == NULL)//nếu cây rỗng
        c = p;
    else //cây khác rỗng
    {
        if (p->iX < c->iX)
            ThemNodeVaoCay(p,c->pLeft);
        else if (p->iX > c->iX)
            ThemNodeVaoCay(p,c->pRight);
        else
            return;
    }
}
void Nhap(Tree &c)
{
    int chon = 0;
    do
    {
        int x ,i=1;
        printf("\n Nhap nut %d : ",i);
        scanf_s("%d",&x);
        Node* p = TaoNode(x);
        ThemNodeVaoCay(p,c);
        printf("Nhap 1 de tiep tuc :");
        scanf_s("%d",&chon);
  i=i+1;
    }while(chon==1);
}
void Xuat(Tree c)
{
    if (c!=NULL)
    {
        if (c->pLeft != NULL)
            Xuat(c->pLeft);
        printf("%4d", c->iX);
        if (c->pRight != NULL)
            Xuat(c->pRight);
    }
}
//Đếm số lượng nút có đúng 1 con mà thông tin tại đó là số nguyên tố
bool SoNguyenTo(int n)
{
    if (n<=1)
        return 0;
    for (int i=2; i<n; i++)
        if (n%i == 0)
            return 0;
    return 1;
}
int Dem(Tree c)
{
    if (c!=NULL)
    {
        int a = Dem(c->pLeft);
        int b = Dem(c->pRight);
        if (SoNguyenTo(c->iX))
            if ((c->pLeft!=NULL && c->pRight==NULL) || (c->pLeft==NULL && c->pRight!=NULL))
                return 1 + a + b;
        return a + b;
    }
    return 0;
}
void main()
{
    Tree c = NULL;
    Nhap(c);
    printf("\n Xuat cay nhi phan LNR: ");
    Xuat(c);
    printf("\n  So luong nut co dung 1 con va gia tri la so nguyen to: %d", Dem(c));
 getch();   
}
Chủ Nhật, 20 tháng 5, 2012
Dem SO Nut Co Dung 1 Con Va Gia Tri La So Nguye To
 Posted by Z-CLICK
Chủ Nhật, tháng 5 20, 2012, under  |  
 
 
 
 
 
 
 
