似乎有些错误,但是错在哪了呢?
#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;
}
错在哪里呢?也许没错。。