我正在尝试实现一个简单的 C++ 函数,该函数在给定要插入的节点的值和 BST 的根的情况下将节点添加到二叉搜索树。
令人惊讶的是,我无法插入任何元素。尽管我确保编译器输入了我插入节点的语句,但树中没有我要添加的任何节点。我认为问题可能在于我如何在函数参数中传递节点。任何人都可以帮忙吗?谢谢。这是我的节点类型和函数的实现。
struct Node{
int value;
Node *left;
Node *right;
};
//this method adds a new node with value v to Binary Search Tree
// node is initially the root of the tree
void Push_To_BST(Node* node,int v)
{
// the right place to add the node
if(node==NULL)
{
node=new Node();
node->value= v;
node->left= NULL;
node->right=NULL;
}
//the value to be added is less than or equal the reached node
else if(v <= node->value)
{
//adding the value to the left subtree
Push_To_BST(node->left,v);
}
//the value to be added is greater than the reached node
else if(v > node->value)
{
//adding the value to the right subtree
Push_To_BST(node->right,v);
}
}
最佳答案
小心你的引用,那里。
void Push_To_BST(Node* node,int v)
{
// the right place to add the node
if(node==NULL)
{
node=new Node();
// etc
您要为其分配内存的节点
是一个本地 变量。您需要传入 Node**
才能将指向新创建节点的指针传出。
例子:
void Push_To_BST(Node** pnode,int v)
{
Node* node = *pnode;
// the right place to add the node
if(node==NULL)
{
node=new Node();
// etc
}
else if(v < node->value)
{
//adding the value to the left subtree
Push_To_BST(&node->left,v);
}
// etc
并称它为
Node* n = new Node;
Push_To_BST(&n, 2);
关于c++ - 将节点插入二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11055014/