[英]Inserting a node into a Binary Search Tree
我正在嘗試實現一個簡單的C ++函數,該函數將給定要插入節點的值和BST的根的節點添加到二進制搜索樹中。
令人驚訝的是,我無法推動任何因素。 盡管我確保編譯器輸入了要插入節點的語句,但是樹沒有要添加的任何節點。 我認為問題可能出在我如何在函數參數中傳遞節點。 有人可以幫忙嗎? 謝謝。 這是我的Node類型和該函數的實現。
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
是局部變量。 您需要在通過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);
您正在分配一個新節點並進行填充,但從未更改現有節點中的指針以指向該新節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.