问题
void Btree<T>::InsertNode2(T data, BtreeNode* root)
{
if (root==NULL)
{
root = new BtreeNode (data);
return ;
}
if (data <= root->data)
InsertNode2(data, root->leftchild);
else
InsertNode2(data, root->rightchild);
}
Why isn't it right? The root can't be assigned correctly. After calling the function it's still NULL.
回答1:
It almost correct. Just, as said by @DragonMoon, all you need to do is to pass root by reference
void Btree<T>::InsertNode2(T data, BtreeNode &* root)
{
if (root==NULL)
{
root = new BtreeNode (data);
return ;
}
if (data <= root->data)
InsertNode2(data, root->leftchild);
else
InsertNode2(data, root->rightchild);
}
来源:https://stackoverflow.com/questions/43373161/how-to-insert-element-in-binary-tree-by-recursion