读书人

请问用一维数组初始化四叉树 小弟我是

发布时间: 2012-02-14 19:19:19 作者: rapoo

请教用一维数组初始化四叉树 我是菜鸟 困惑了好久了 大虾们救救俺
平台vc6.0 ,我的目的是把数组的16个元素分别赋给四叉树的所有叶节点的color变量,而其他非叶节点的color值赋0(可以看做是用位图像素建立四叉树),但运行始终不对 单步调试的时候发现,第一次迭代就把根节点清零了,百思不得其解,请高手指点


代码如下
int TreeValue3[16]={0,1,1,0,1,1,0,1,0,1,0,1,0,0,0,1};//相当于位图的像素部分,16个像素,大小4*4
int m=2;

struct dib
{
int color;

dib *nw;//2象限
dib *ne;//1象限
dib *sw;//3象限
dib *se;//4象限

};
typedef struct dib DIBTREE;


void CreateBTree2(int *pARRAY,int width,int height,DIBTREE *p)
{
p=(DIBTREE *)new(DIBTREE);
while (p)
{
if (m<=4)
{
p->color=0;
p->nw=(DIBTREE *)pARRAY;
p->ne=(DIBTREE *)(pARRAY+int(width/m));
p->sw=(DIBTREE *)(pARRAY+width*(int(height/m)));
p->se=(DIBTREE *)(pARRAY+width*(int(height/m))+int(width/m));

int *pANW=pARRAY;
int *pANE=pARRAY+int(width/m);
int *pASW=pARRAY+width*(int(height/m));
int *pASE=pARRAY+width*(int(height/m))+int(width/m);
m=m*2;

pARRAY=pANW;
CreateBTree2(pARRAY,width,height,p->nw);
pARRAY=pANE;
CreateBTree2(pARRAY,width,height,p->ne);
pARRAY=pASW;
CreateBTree2(pARRAY,width,height,p->sw);
pARRAY=pASE;
CreateBTree2(pARRAY,width,height,p->se);
}
else
{
p->nw=p->ne=p->se=p->sw=NULL;
p->color= *pARRAY;
cout<<p->color<<endl;
return;
}
}

}






int main()
{

int *pARRAY=TreeValue3;
DIBTREE *p;
CreateBTree2(pARRAY,4,4,p);
return 0;

}

[解决办法]
void CreateBTree2(int *pARRAY,int width,int height,DIBTREE *p)
执行结束后p不会保存下来

p-> nw=(DIBTREE *)pARRAY;
把int *变成DIBTREE *,逻辑错误吧


[解决办法]
楼主的代码看得不太明白,但是你DIBTREE *p;
CreateBTree2(pARRAY,4,4,p);
void CreateBTree2(int *pARRAY,int width,int height,DIBTREE *p)
这里得指针用法很有问题。建议改为
DIBTREE *p1;
p1=(DIBTREE *)new(DIBTREE);
CreateBTree2(pARRAY,4,4,p1);
[解决办法]
你描述的功能并不复杂啊,但是感觉代码写的很乱,可以把递归什么都省去不,老老实实的建棵树,按数组的指针赋好值,就ok了。

读书人网 >软件架构设计

热点推荐