计算二进制搜索树中的平均数

时间:2014-11-23 14:36:38

标签: c binary-search-tree average

我想计算平均值。树有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);}

此代码无法正常运行。你认为我通过递归方式调用普通方法吗?

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}

答案 2 :(得分: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