2014-11-23 32 views
-2

我想計算平均值。樹有4個信息:數據,數字,左和右。所有節點的平均值=數據和數量/總數的乘積。計算二叉搜索樹中的平均數

struct node{ 
int number; 
int data; 
struct node *right; 
struct node *left; 
} 
typedef struct node nod; 
typedef struct node* nodePtr; 
typedef struct node** nodePtrPtr; 
int main(){ 
nodePtr a=NULL; 

calAverage(&a); 
} 
void calAverage(nodePtrPtr tree){ 
{ 
    nodePtr g; 
    double average, sum=0,num,n,s=0; 
    int k,z=0; 
    int l,w=0; 

    if(tree){ 
    tree=g; 
    g->total_number_of_reviews=k; 
    g->scoreNumber=num; 
    sum+=(num*k); 
    z+=k; 
    } 


    if(tree->left){ 
    calAverage(tree->left);   
    } 

    if(tree->right){ 
    calAverage(tree->right);  
    } 

average=((sum+s)/(z+w)); 
printf("%.1lf average ",average);} 

此代碼不能正常工作。你認爲我遞歸地調用平均方法嗎?

+1

1)結構節點權利的'構件; struct node left;' - >'* right','* left' – BLUEPIXY 2014-11-23 14:46:53

+0

2)'nodePtr a; calAverage(&a);':'a'是未初始化的,它沒有賦值 – BLUEPIXY 2014-11-23 14:49:35

+0

其實我寫這些但不添加此頁面,但我的問題是關於calAverage方法 - >是否爲true?@BLUEPIXY – elminaa 2014-11-23 14:51:58

回答

0

就做遞歸

,並嘗試這個辦法:

struct node{ 
    int number; 
    int data; 
    struct node *right; 
    struct node *left; 
}; 


void calAverage(node *tree) 
{ 

    node *g; 
    double average, sum=0,num,n,s=0; 
    int k,z=0; 
    int l,w=0; 
    g=tree; 

    while(g != NULL){ 
     k=g->number; 
     num=g->data; 
     sum+=(num*k); 
     z+=k; 
     g=g->right; 
     while(g != NULL){ 
      l=g->number; 
      n=g->data; 
      s+=(n*l); 
      w+=l; 
      g= g->left; 
     } 
    } 
    average=((sum+s)/(z+w)); 
    printf("%.1lf average ",average); 
} 


int main(int argc) 
{ 
    node *a=NULL; 
    calAverage(a); 

    scanf("%d"); 
    return 0; 
} 
0

我通過定義存儲number*data所有數據的價值,並和兩個全局變量這樣做。 然後簡單遞歸

s=sumofproduct 
p=sumofdata 

void average(node *ptr,int *s,int *p) 
{ 
    if(ptr==NULL) 
    { 
    return ;  
    } 
    int k=ptr->data; 
    int l=ptr->number; 
    *p=(*p)+k*l; 
    *s=*s+ptr->data;  
    if(ptr->left) 
    average(ptr->left,s,p); 
    if((ptr->right)) 
    average(ptr->right,s,p); 
} 

然後在主我印sumofproduct/sumofdata

1

示例代碼

struct tree { 
    int value; 
    struct tree *left; 
    struct tree *right; 
}; 

int sum(struct tree *root){ 
    if(root == NULL) 
     return 0; 
    return root->value + sum(root->right) + sum(root->left); 
} 
int count(struct tree *root){ 
    if(root == NULL) 
     return 0; 
    return 1 + count(root->right) + count(root->left); 
} 
double ave(struct tree *root){ 
    return (double)sum(root)/count(root); 
} 
void sum_count(struct tree *root, int *sum, int *count){ 
    if(root != NULL){ 
     *sum += root->value; 
     ++*count; 
     sum_count(root->left, sum, count); 
     sum_count(root->right, sum, count); 
    } 
} 
double ave2(struct tree *root){ 
    int sum=0, count=0; 
    sum_count(root, &sum, &count); 
    return (double)sum/count; 
}