KD树插入

时间:2015-03-15 18:05:33

标签: c++

//inserts a node into the KD tree
void KDTree::insert(KDNode *point){
//If there is nothing to insert
if (point == NULL) return; 

//If the root points to nothing
if (root == NULL){
    root = point; 
    root->left = NULL; 
    root->right = NULL;
    return; 
}

insertKD(point, root); 
}

//helper function to facilitate recursion 
void KDTree::insertKD(KDNode *point, KDNode *r){
//If the point is already in the tree, don't store it
if (point->coordinates.getX() == r->coordinates.getX() && point->coordinates.getY() == r->coordinates.getY()){
    return;
} 

//save key value of parent
int key = r->key; 

//when the key is 0, we compare x-values
if (key == 0){
    //if the x-value of the point is less than the parent's store it at the left
    if (point->coordinates.getX() < r->coordinates.getX()){
        if (r->left == NULL){
            r->left = point;
            //set key to 1 since its parent has key 0
            point->key = 1; 
            return; 
        }
        else insertKD(point, r->left);
    }

    //if the x-value of the point is more than or equal the parent's store it at the right
    if (point->coordinates.getX() >= r->coordinates.getX()){
        if (r->right == NULL){
            r->right = point; 
            //set key to 1 since its parent has key 0
            point->key = 1; 
            return; 
        }
        else insertKD(point, r->right);
    }
}

//when the key is 1, we compare y-values 
if (key == 1){
    //if the y-value of the point is less than the parent's store it at the left
    if (point->coordinates.getY() < r->coordinates.getY()){
        if (r->left == NULL){
            r->left = point; 
            //set key to 0 since its parent has key 1
            point->key = 0;
            return; 
        }
        else insertKD(point, r->left);
    }

    //if the y-value of the point is more than or equal the parent's store it at the right
    if (point->coordinates.getY() >= r->coordinates.getY()){
        if (r->right == NULL){
            r->right = point; 
            //set key to 0 since its parent has key 1
            point->key = 0;
            return; 
        }
        else insertKD(point, r->right);
    }
}  
} 

当我测试树是否工作时,我意识到它没有正确插入元素(它只插入第一个)。我有一个for循环,为类类型分配内存,然后使用此函数。我进入调试模式,看看指针指向的位置。第一次(i = 0)我分配的新对象指向一个内存值(预期),然后在下一个循环(i = 1),root指向相同的内存值(也是预期的),但当我调用函数再次插入,在第三个循环中,root-&gt; left或root-&gt; right的值不指向任何东西(它只是说0x0,我的构造函数将它们初始化为NULL)。我手动完成的代码出了什么问题,它似乎在逻辑上有效?

0 个答案:

没有答案