所以我有一段代碼,我必須在其中向 BST 添加一個節點。我的結構如下:
typedef struct _CC_TREE {
// Members
int Value;
struct _CC_TREE* LChild;
struct _CC_TREE* RChild;
} CC_TREE;
頭檔案中的插入函式如下所示:
int TreeInsert(CC_TREE *Tree, int Value);
我必須回傳插入的狀態。
我嘗試用另一個函式做它并將它添加到樹
CC_TREE* InsertNewNode(CC_TREE* Tree, int Value)
{
if (NULL == Tree)
{
Tree = (CC_TREE*)malloc(sizeof(CC_TREE));
Tree->LChild = NULL;
Tree->RChild = NULL;
Tree->Value = Value;
return Tree;
}
if (Value <= Tree->Value)
{
Tree->LChild = InsertNewNode(Tree->LChild, Value);
}
else if (Value >= Tree->Value)
{
Tree->RChild = InsertNewNode(Tree->RChild, Value);
}
return Tree;
}
int TreeInsert(CC_TREE *Tree, int Value)
{
CC_UNREFERENCED_PARAMETER(Tree);
CC_UNREFERENCED_PARAMETER(Value);
Tree = InsertNewNode(Tree, Value);
return 0;
}
我嘗試在我的主要功能中構建樹:
int retVal = -1;
CC_TREE* usedTree = NULL;
retVal = TreeCreate(&usedTree);
if (0 != retVal)
{
printf("TreeCreate failed!\n");
goto cleanup;
}
retVal = TreeInsert(usedTree, 20);
if (0 != retVal)
{
printf("TreeInsert failed!\n");
}
但由于某種原因,usedTree仍然為空。我知道我應該CC_TREE** Tree在插入函式中使用,但我不被允許。
uj5u.com熱心網友回復:
頭檔案中的插入函式如下所示:
int TreeInsert(CC_TREE *Tree, int Value);
如果您無法更改函式簽名或(ew!)使用全域變數將根指標回傳給呼叫者,那么您最好的選擇可能是使用虛擬樹根。看起來像這樣:
int TreeInsert(CC_TREE *Tree, int Value) {
// Tree points to a dummy root node containing no data.
// Tree->LChild is the actual root pointer
CC_TREE *root = Tree->LChild;
int status = 0;
// ... perform insertion, possibly resulting in a different value for the
// root pointer ...
Tree->LChild = root;
return status;
}
這假定 to 的第一個引數TreeInsert()始終是指向 a 的有效指標CC_TREE。如果你這樣做,那么所有其他樹函式都應該類似地作業。
你會main()像這樣使用它:
int retVal;
CC_TREE dummy_tree_root = { 0 };
retVal = TreeInsert(&dummy_tree_root, 42);
請注意,這種方法實際上是通過間接路由使用雙指標(不是雙關語)。ACC_TREE *本身不是雙指標,但在該指標與其指向的節點的左子節點或右子節點之間仍然存在兩級間接性。
另請注意,執行此操作的更簡潔的方法將涉及提供表示整個樹的包裝器結構,而不是為此目的使用裸樹節點或樹節點指標。資料結構將是這樣的:
struct node {
int value;
struct node *left;
struct node *right;
};
struct tree {
struct node *root;
// optionally other data, such as size, height, etc.
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/430162.html
