How to insert element in binary tree by recursion?

筅森魡賤 提交于 2019-12-11 05:49:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!