构造次优查找树

似乎有些错误,但是错在哪了呢?

#include <iostream>
#include <cmath>
using namespace std;


const int NUM = 9;


int value[NUM] = {1,2,3,4,5,6,7,8,9};
float weight[NUM] = {1,1,2,5,3,4,4,3,5};
float sum_weight[NUM];
void init_sum_weight(){
    int sum = 0;
    for(int i = 0; i <= NUM; i++){
        sum += weight[i];
        sum_weight[i] = sum;    
    }
}
struct Tree{
    float weight;
    int value;
    Tree* left;
    Tree* right;
    ~Tree(){delete left; delete right;}
}(*tree);
void mid(Tree (*tree)){
    if(!tree)return;
    cout<<tree->value<<"(";
    if(tree->left)
        cout<<tree->left->value;
        cout<<",";
    if(tree->right)
        cout<<tree->right->value;
        cout<<")"<<" ";
    mid(tree->left);
    mid(tree->right);
}


void pre(Tree (*tree)){
    if(!tree)return;
    pre(tree->left);
    cout<<tree->value<<" ";
    pre(tree->right);
}
//Δpi = sum[h] - sum[i] - sum[i - 1];
void constructTree(Tree *(*tree), int h, int l){
    int min, dw, hit = l;
    if(l != 0){
        min = abs(sum_weight[h] - sum_weight[l] - sum_weight[l-1]);//Δpl
        dw = abs(sum_weight[h] + sum_weight[l-1]);
    }else{
        min = abs(sum_weight[h] - sum_weight[l]);
        dw = abs(sum_weight[h]);
    }
    for(int i = l+1; i <=h; i++){
        int new_min = abs(sum_weight[h] - sum_weight[i] - sum_weight[i-1]);//Δpi
        if(new_min < min){
            min = new_min;
            hit = i;
        }
    }
    (*tree) = new Tree;
    (*tree)->weight = weight[hit];
    (*tree)->value = value[hit];
    cout<<"value="<<value[hit]<<endl;
    if(hit == l){
        (*tree)->left = NULL;//左
    }else{
        constructTree(&(*tree)->left, hit-1, l);
    }
    if(hit == h){
        (*tree)->right = NULL;
    }else{
        constructTree(&(*tree)->right, h, hit+1);
    }
}
int main(){
    Tree (*tree);
    init_sum_weight();
    constructTree(&tree, NUM-1, 0);
    cout<<"mid:";
    mid(tree);
    cout<<endl;
    cout<<"pre:";
    pre(tree);
    cout<<endl;
    delete tree;
}

错在哪里呢?也许没错。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值