【问题标题】:How to insert element in binary tree by recursion?如何通过递归在二叉树中插入元素?
【发布时间】:2017-04-12 15:00:13
【问题描述】:
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);
}

为什么不对?无法正确分配根。调用函数后它仍然是 NULL。

【问题讨论】:

标签: binary-tree


【解决方案1】:

这几乎是正确的。只是,正如@DragonMoon 所说,您需要做的就是通过引用传递root

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);
}

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 2012-11-16
    • 2020-07-24
    • 2014-12-03
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多