在我的 BST 实现中,我的 findNode 函数没有将父位置返回给其调用函数

In my BST implementation,my findNode function not returning parent location to its calling function

本文关键字:函数 我的 位置 返回 调用 实现 BST findNode      更新时间:2023-10-16

在实现二叉搜索树时,我尝试拥有一个自定义查找成员函数(findNode),它可以为我提供节点位置以及父位置,但它未能将其返回给调用函数。

在实现二叉搜索树时,我尝试使用自定义查找成员函数(findNode),它可以为我提供节点位置以及父位置。 如果我在 findNode 内部检查,它能够找到父位置。但它未能将其返回到调用函数。

#include<iostream>
using namespace std;
struct node
{
struct node* left;
int data;
struct node* right;
};
typedef struct node myNode;
class myTree
{
myNode* root;
void inorderUtil(myNode* rt);
public:
myNode* createNode(int num);
myTree():root(NULL){};
void inorder();
//void postorder();
//void preorder();
void findNode(int num,myNode* par,myNode* loc);
void insertNode(int num);
void displayroot(){cout<<root->data<<endl;}
};
void myTree::inorder()
{
inorderUtil(root);
}
void myTree::inorderUtil(myNode* rt)
{
if(rt != NULL)
{
inorderUtil(rt->left);
cout<<rt->data<<endl;
inorderUtil(rt->right);
}
}
myNode* myTree::createNode(int num)
{
myNode* nd= new myNode();
nd->data=num;
nd->left=NULL;
nd->right=NULL;
return nd;
}
void myTree::findNode(int num,myNode* par,myNode* loc)
{
cout<<"Searching for "<<num<<endl;
if(root==NULL)
{
par=NULL;
loc=NULL;
//cout<<"tree is empty"<<endl;
return;
}
if(root->data==num)
{
par=NULL;
loc=root;
return;
}
//cout<<"tree is non empty and data not at root"<<endl;
myNode* r=root;
par=root;
loc=NULL;
while((r->left != NULL) || (r->right != NULL))
{
if(r->left!=NULL && (r->left->data ==num))
{
par=r;
loc=r->left;
break;
}
else if(r->right!=NULL && (r->right->data ==num))
{
par=r;
loc=r->right;
break;
}
else
{
par = r;
if(num < r->data)
r = r->left;
else
r = r->right;
}
}
cout<<"parent is ="<<par->data<<endl;
}

void myTree::insertNode(int num)
{

myNode* par=NULL;
myNode* loc=NULL;
findNode(num,par,loc);
if(par !=NULL)
{
cout<<"in insert parent is ="<<par->data<<endl;
}
if(loc != NULL)
{
cout<<num<<" is already in tree, Aborting insertion "<<endl;
}
else    
{
myNode *nd= createNode(num);
if(par == NULL)
{
root=nd;
}
else
{
if(par->left == NULL && par->data >num)
par->left =nd;
if(par->right == NULL && par->data <num)
par->right =nd;
}
}
}
int main()
{
myTree tr;
tr.insertNode(50);
tr.displayroot();
myNode* par=NULL;
myNode* loc=NULL;
tr.findNode(40,par,loc);
if(par!=NULL)
{
cout<<"parent from main is=="<<par->data<<endl;
}

return 0;
}

它也应该打印在下面几行:- 主父是==

您似乎忘记了默认情况下C++中的参数是按值传递的。 这意味着参数的值被复制到函数的局部变量中。

如果你想给调用方一个值,要么返回它(例如std::pair<myNode*, myNode*>) 或通过引用传递指针(例如myNode*& par)。