[英]Binary Tree search returns no results (C++)
我正在研究一些二叉樹算法,需要一個“使用searchindex ...查找節點”功能。 treenodes的設計基本上是
class TreeNode {
int index; // some identifier
TreeNode *left;
TreeNode *right;
}
並且樹由指向根節點的指針定義。
我對搜索功能的實現是:
void Tree::searchNode(TreeNode * root, int nodeIndex, TreeNode *resultNode){
/* Recursive search */
if (root->index == nodeIndex) {
resultNode = root;
} else {
/* search children if the current node is not a leaf */
if(!root->isLeaf()) {
this->searchNode(root->left,nodeIndex,resultNode);
this->searchNode(root->right,nodeIndex,resultNode);
}
}
}
參數: * root是樹的根節點, nodeIndex是search-index,* resultNode是指向樹中找到(或不是)節點的指針。
該函數不返回指向找到的節點的引用或指針,但修改指針resultNode ,使其指向找到的節點。 我們的想法是使用NULL初始化resultNode,執行搜索並在匹配發生時修改它。 否則它仍然是NULL,我可以很容易地檢查是否有搜索結果。
具有樹構建樹的另一個類作為成員以這種方式利用搜索功能:
TreeNode *resultNodePtr = NULL;
this->buildingTree->searchNode(this->buildingTree->rootPtr,
currentNodeIndex, resultNodePtr);
// do sth. with resultNodePtr if != NULL
我在堆棧上創建* resultNodePtr ,因為我只需要暫時在函數內部。 這樣做是否正確? 但是:該功能不起作用。 即使樹包含帶有search-index的節點, resultNodePtr也始終為NULL。 我一步一步地仔細調試它,它檢測到
(root->index == nodeIndex)
正確但是
resultNode = root;
不起作用(我希望resultNode指向相同的地址根點)。 調試器說resultNode前分配為0x0, 根節點是一些ADRESS,分配resultNode仍然為0x0后。
我是否必須重載operator =在本例中是否為TreeNode類?
我試過了:
TreeNode & TreeNode::operator=(const TreeNode & oldTreeNode){
*this = oldTreeNode;
return *this;
// ignore childs for now
}
我不是專家,但這個算子似乎微不足道。 它是否會影響兩個TreeNode指針* node1 = * node2的賦值?
也許你可以幫助我。 感謝您的閱讀,感謝您的幫助。 如果我自己找到解決方案,我會在這里發布。
問候,馬克
因為您將resultNode
作為指針按值傳遞給函數,所以它的原始值永遠不會改變。 將TreeNode*
視為字面上只不過是一個代表內存地址的數字; 當你重新分配時:
resultNode = root;
這會修改searchNode
具有的副本,但不會修改調用searchNode
的代碼中的原始指針。 舉個簡單的例子:
void Foo(int x)
{
x = 100;
}
void Bar()
{
int x = 0;
Foo(x);
// at this point, x is still 0
}
resultNode
的值不會從NULL
更改,原因與調用函數Bar
時x
不會從0
更改的原因相同。 要解決此問題,請將指針作為指針傳遞給指針,或者通過引用傳遞指針:
void Tree::searchNode(TreeNode* root, int nodeIndex, TreeNode*& resultNode)
{
// same code
}
... 要么:
void Tree::searchNode(TreeNode* root, int nodeIndex, TreeNode** resultNodePtr)
{
// assign to *resultNodePtr instead
}
您的resultNode指針是按值傳遞的,而不是通過引用傳遞的。 因此,當函數調用完成時,調用端的指針不會收到值。
你的算法看起來很好:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.