小编aar*_*rns的帖子

在二叉树中插入4或5个数字,但在输出中只获得3个数字

这是学校处理递归和二叉树的实验室的一部分.如果我要插入4或5个数字并输出结果,我只得到3个数字.这是插入的代码:

Node *insert(Node *t, int key) {
    Node *insertParent;
    Node *result=NULL;

    if (t!=NULL) {
        result=search(t,key,insertParent);
    } else {
        t=new Node;
        t->data=key;
        t->leftchild=NULL;
        t->rightchild=NULL;
        return t;
    }

    if (result==NULL) {
        if (insertParent->data>key) {
            insertParent->leftchild=new Node;
            insertParent->leftchild->data=key;
            insertParent->leftchild->leftchild=NULL;
            insertParent->leftchild->rightchild=NULL;
            return insertParent->leftchild;
        } else if (insertParent->data<key) {
            insertParent->rightchild=new Node;
            insertParent->rightchild->data=key;
            insertParent->rightchild->leftchild=NULL;
            insertParent->rightchild->rightchild=NULL;
            return insertParent->rightchild;
        }
    } else
        return NULL;
}
Run Code Online (Sandbox Code Playgroud)

但我相信问题在于搜索功能,特别是引用父节点指针:

Node* search(Node *t, int key, Node *&parent) {
    if (t!=NULL) {
        parent=t;
        if (t->data==key)
            return t;
        else if (t->data>key)
            return search(t->leftchild,key,t);
        else …
Run Code Online (Sandbox Code Playgroud)

c++ recursion binary-tree

5
推荐指数
1
解决办法
206
查看次数

标签 统计

binary-tree ×1

c++ ×1

recursion ×1