Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

#include <iostream>

#include <ctime>
using namespace std;
struct node
{
int data;
struct node* pLeft;
struct node* pRight;
};
typedef struct node NODE;
typedef NODE* TREE;

void khoiTaoCay(TREE& t)
{
t = NULL;
}

void themNODEVaoCay(TREE& t, int n)


{
if (t == NULL)
{
NODE* p = new NODE;
p->data = n;
p->pLeft = NULL;
p->pRight = NULL;
t = p;
}
else
{
if (n < t->data)
{
themNODEVaoCay(t->pLeft, n);
}
else if (n > t->data)
{
themNODEVaoCay(t->pRight, n);
}
}
}
void taoCayVoiGiaTriNgauNhien(TREE& t, int n)
{
srand(time(NULL));
for (int i = 0; i < n; i++)
{
int x = rand() % 1000 - 1;
themNODEVaoCay(t, x);
}
}

bool check_So_ArmStrong(int n)
{
int temp;
int tong = 0;
int copy_of_num = n;
while (n > 0)
{
temp = n % 10;
tong = tong + (temp * temp * temp);
if (tong == copy_of_num)
{
return true;
}
n /= 10;
}
return false;
}

void dem_So_ArmStrong(TREE t, int& dem)


{
if (t != NULL)
{
if (check_So_ArmStrong(t->data) == true)
{
dem++;
}
dem_So_ArmStrong(t->pLeft, dem);
dem_So_ArmStrong(t->pRight, dem);
}
}

void tinhTong_So_ArmStrong(TREE t, int& tong)


{
if (t != NULL)
{
if (check_So_ArmStrong(t->data) == true)
{
tong += t->data;
}
tinhTong_So_ArmStrong(t->pLeft, tong);
tinhTong_So_ArmStrong(t->pRight, tong);
}
}

void duyetCay_NLR(TREE t)
{
if (t != NULL)
{
cout << t->data << "\t ";
duyetCay_NLR(t->pLeft);
duyetCay_NLR(t->pRight);
}
}
int nhapn() {
int n;
do {
cout << "Nhap so nguyen: ";
cin >> n;
if (n >= 1 && n <= 1000) return n;
} while (true);
}

int main() {
TREE t;
khoiTaoCay(t);
cout << "CAU 1 :\n";
int n;
n = nhapn();
cout << "\n CAU 2 :\n";
taoCayVoiGiaTriNgauNhien(t, n);
duyetCay_NLR(t);
cout << "\nCAU 3 :\n";
int tong, dem;
tinhTong_So_ArmStrong(t, tong);
dem_So_ArmStrong(t, dem);
cout << dem<<endl;
cout << tong << endl;
if (dem == 0) {
cout << "khong ton tai so Amstrong ";
}
else {
cout << "Gia Tri TBC Cua So AmStrong La : " << (float)tong / dem;
}
system("pause");

You might also like