Tính trung bình cộng các giá trị trên cây nhị phân.
#include <stdio.h>
#include <math.h>
#include<conio.h>
struct Node{
Node *pleft, *pright;
int iX;
};
typedef Node* Tree;
Node* TaoNode(int X){
Node *p;
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) c = p;
else{
if (p->iX < c->iX) ThemNodevaocay(p, c->pleft);
if (p->iX>c->iX) ThemNodevaocay(p, c->pright);
else return;
}
}
void Nhap(Tree &c){
int chon = 0;
do{
int x;
printf("\nNhap vao x: ");
scanf("%d", &x);
Node* p = TaoNode(x);
ThemNodevaocay(p, c);
printf("Muon nhap tiep (an 0 de ket thuc)");
scanf("%d", &chon);
} while (chon);
}
int DemNode(Tree c)
{
if (c == NULL)
return 0;
int a = DemNode(c->pright);
int b = DemNode(c->pleft);
return a + b + 1;
}
int TinhTong(Tree c){
if (c != NULL){
int a = TinhTong(c->pleft);
int b = TinhTong(c->pright);
return c->iX + a + b;
}
return 0;
}
int main()
{
int x;
Node *P;
Tree c = NULL;
Nhap(c);
printf("\n Gia tri trung binh cong la: %f", (float)TinhTong(c) / DemNode(c));
getch();
return(0);
}
Thứ Bảy, 30 tháng 5, 2015
Tính trung bình cộng các giá trị trên cây nhị phân
Đăng ký:
Đăng Nhận xét (Atom)
0 nhận xét:
Đăng nhận xét