微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

递归二叉树函数

如何解决递归二叉树函数

| 我正在尝试将数组中的项目插入树中。我的函数运行良好,并一直创建到树左侧的叶节点的节点。问题是当检测到较高级别的叶节点时应该递归返回时,它只是完全停止构建树。这是代码
void WLD::treeInsert(BSP_Node *tree_root,int node_number)

{

if ( tree_root == NULL ) 
    {
        tree_root = new BSP_Node();

        tree_root->node_number = node_number;
        tree_root->normalX = bsp_array[node_number].normal[0];
        tree_root->normalY = bsp_array[node_number].normal[1];
        tree_root->normalZ = bsp_array[node_number].normal[2];
        tree_root->splitdistance = bsp_array[node_number].splitdistance;;
        tree_root->region = bsp_array[node_number].region;
        tree_root->left = bsp_array[node_number].left; //because the array starts at index 0
        tree_root->right = bsp_array[node_number].right; //because the array starts at index 0
        tree_root->left_node = NULL;
        tree_root->right_node = NULL;

        errorLog.OutputSuccess(\"Inserting new node: %i\",node_number);
        errorLog.OutputSuccess(\"Left node index: %i\",bsp_array[node_number].left);
        errorLog.OutputSuccess(\"Right node index: %i\",bsp_array[node_number].right);

        node_number++;

        // Check for leaf nodes
        if(tree_root->region != 0)
        {
            errorLog.OutputSuccess(\"This is a leaf node! Returning!\");
            return;
        }
    }


    if ( tree_root->left > 0) 
    {
        //tree_root->left_node = new BSP_Node();
        errorLog.OutputSuccess(\"Left node not NULL,inserting it!\");
        treeInsert( tree_root->left_node,tree_root->left );
    }
    else if (tree_root->right > 0)
    {
        //tree_root->right_node = new BSP_Node();
        errorLog.OutputSuccess(\"Right node not NULL,inserting it!\");
        treeInsert( tree_root->right_node = NULL,tree_root->right );
    }

}
如您所见,当它检测到叶子节点时,它应该返回到调用函数(此函数在离该节点更近的级别上。有人有任何建议吗?     

解决方法

        
if ( tree_root->left > 0)  {
   // implementation
}
else if (tree_root->right > 0) {
   // implementation
}
这不是两个单独的if语句,而不是if / else吗?否则,它只会做任何一方,而不会做任何一方。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。