c++ - 递归二叉树函数

标签 c++ recursion binary-tree

我正在尝试将我的数组中的项目插入到我的树中。我的函数工作正常并创建节点一直向下到树左侧的叶节点。问题是当它应该在检测到更高级别的叶节点时递归返回时,它只是完全停止构建树。这是代码:

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 吗?否则它只会做一侧或另一侧,而不是同时做。

关于c++ - 递归二叉树函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6185137/

相关文章:

Python:当网格大小太大时,遍历网格的递归调用计数方式会产生不正确的答案

javascript - 我将如何编写一个递归函数来对使用尾调用优化 (TCO) 的数字数组求和?

java - 构造java树数据

c++ - 如何修复 Level Order Traversal Problem (Binary Trees) 的这个无限循环错误

C++ CppUnitTest (CPPUNIT_ASSERT_EQUAL)

c++ - 如何在离线状态下检测当前的 Windows 更新状态?

c++ - boost::asio::async_accept 处理程序未被调用

python - Python 中的递归问题

mysql - MySQL数据库索引中的 "seq_in_index"是什么意思?

c++ - 与 boost::interprocess_mutex 相比,为什么不在共享内存中使用 boost::mutex 呢?