我正在構建一棵二叉樹。二叉樹預構建在一個文件中,我需要構建它。由於它的結構化方式,我將這棵樹讀入一個數組中。每個樹節點看起來像這樣。來自預先計算樹的樹木構建函數
struct Tree_Node
{
float normalX;
float normalY;
float normalZ;
float splitdistance;
long region;
long left, right; //array index
Tree_Node* left_node; // pointer to left node
Tree_Node* right_node; // pointer to right node
} typedef Tree_Node;
我已經嘗試了很多方法來編寫一些代碼來構建樹。讓我給你一些僞代碼,讓你明白我想要做什麼。
- 讀入頭節點。節點是陣列中的第一名。
- 如果節點具有左右數組索引,則創建新節點並從數組 中插入指示信息到該樹節點。
- 如果節點沒有右側和左側索引,則它是葉節點。
這裏是我的建築功能:
void WLD::treeInsert(BSP_Node *tree_root, int node_number)
{
/// Add the item to the binary sort tree to which the parameter
// "root" refers. Note that root is passed by reference since
// its value can change in the case where the tree is empty.
if (tree_root == NULL)
{
// The tree is empty. Set root to point to a new node containing
// the new item. This becomes the only node in the tree.
tree_root = new BSP_Node();
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;
tree_root->right = bsp_array[node_number].right;
tree_root->left_node[node_number];
tree_root->right_node[node_number];
errorLog.OutputSuccess("Inserting new root node: %i", node_number);
// NOTE: The left and right subtrees of root
// are automatically set to NULL by the constructor.
// This is important...
}
if (tree_root->left != 0)
{
errorLog.OutputSuccess("Inserting left node number: %i!", tree_root->left);
treeInsert(tree_root->left_node, tree_root->left);
}
else if ( tree_root->right != 0)
{
errorLog.OutputSuccess("Inserting right node: %i!", tree_root->right);
treeInsert(tree_root->right_node, tree_root->right);
}
else if (tree_root->right == 0 && tree_root->left == 0)
{
errorLog.OutputSuccess("Reached a leaf node!");
return;
}
else
{
errorLog.OutputError("Unknown BSP tree error!");
}
}
我調試表明,該函數試圖插入節點2,直到程序崩潰。
有人可以幫助我嗎?
這功課嗎?如果是這樣,你能把它標記爲這樣嗎? – tjameson 2011-05-31 07:28:02
請使用格式化功能,以減輕每個人對你下一個問題的理解:) – ereOn 2011-05-31 07:29:11
@tjameson這不是家庭作業。我正在嘗試從Quake引擎中操縱BSP格式。 – 2011-05-31 07:37:10