jianingkid 于 2013.12.07 19:32 提问

kd树插入问题，程序没有问题，但是运行无法达到理想！达人速进啊！

{
int a[2];
int deep;
int h,left,right;
kd *leftchild;
kd *rightchild;
}kdt;

// kd.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
void inittree(kdt **R)
{
*R=(kdt *)malloc(sizeof(kdt));
(*R)->leftchild=NULL;
(*R)->rightchild=NULL;
(*R)->deep=0;
(*R)->h=0;
(*R)->left=0;
(*R)->right=0;
}

insert(kdt *q,kdt *T)
{
/*for(int i=0;i<2;i++)
{

``````        printf("%d ",q->a[i]);
}*/

kdt *p;
``````

p=T;

``````if(p->h==0)
{
for(int i=0;i<2;i++)
{
p->a[i]=q->a[i];
//printf("%d ",p->a[i]);

}
p->h=1;
printf("插入根节点成功\n");
``````

return 1;
}

int i=T->deep%2;

if(T->a[i]>q->a[i])//左
{
q->deep++;
printf("l插%d入%d成%d功%d\n",T->left,T->deep,T->a[i],i);
if(T->left)
insert(q,T->leftchild);
else
{
T->left=1;
T->leftchild=q;
return 1;
}
}

``````        else//右
{
q->deep++;
printf("r插%d入%d成%d功%d\n",T->right,T->deep,T->a[i],i);
if(T->right)
insert(q,T->rightchild);
else
{
T->right=1;
T->rightchild=q;
return 1;
}
}
``````

return 0;
}

int main(int argc, char* argv[])
{
int k;
kdt *root,*q,*T;
inittree(&root);

``````inittree(&T);
T=root;

//  printf("%d",q->deep);
inittree(&q);
``````

printf("请输入结点坐标：");
for(int i=0;i {
scanf("%d",&q->a[i]);
}

``````            q->deep=0;
q->h=1;

i=insert(q,T);
if(i)printf("插入成功");
else printf("插入失败");

return 0;
``````

}