aar*_*rns 5 c++ recursion binary-tree
这是学校处理递归和二叉树的实验室的一部分.如果我要插入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
return search(t->rightchild,key,t);
} else
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
我有一个输出树的功能,并在我手动构建的树上检查它,它工作正常:
void inorder(Node *t)
{
if (t!=NULL) {
if (t->leftchild!=NULL)
inorder(t->leftchild);
cout << t->data << ", ";
if (t->rightchild!=NULL)
inorder(t->rightchild);
}
}
Run Code Online (Sandbox Code Playgroud)
不寻找答案只是寻找我应该看的区域.
所以我发现我的问题出在搜索功能上。它确实与引用父节点变量有关。我必须使用四个 else/ifelse 语句才能决定走哪条路,是否递归。
Node* search(Node *t, int key, Node *&parent) {
if (t!=NULL) {
if (t->data==key) {
parent=NULL;
return t;
} else if (t->data>key && t->leftchild!=NULL) {
return search(t->leftchild,key,parent); // think this needs returned
} else if (t->data>key && t->leftchild==NULL) {
parent=t;
return NULL;
} else if (t->data<key && t->rightchild!=NULL) {
return search(t->rightchild,key,parent); //think this needs returned
} else if (t->data<key && t->rightchild==NULL) {
parent=t;
return NULL;
}
} else {
parent=NULL;
return NULL;
}
}
Run Code Online (Sandbox Code Playgroud)
搜索功能的更改需要对插入功能进行更改:
Node *insert(Node *t, int key) {
Node *insertParent=NULL;
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 (insertParent==NULL && result!=NULL) {
return NULL;
} else if (insertParent!=NULL && result==NULL) {
//key not found need to add
if (insertParent->data>key) {
insertParent->leftchild=new Node;
insertParent->leftchild->data=key;
insertParent->leftchild->leftchild=NULL;
insertParent->leftchild->rightchild=NULL;
return insertParent->leftchild;
} else {
insertParent->rightchild=new Node;
insertParent->rightchild->data=key;
insertParent->rightchild->leftchild=NULL;
insertParent->rightchild->rightchild=NULL;
return insertParent->rightchild;
}
}
}
Run Code Online (Sandbox Code Playgroud)
感谢所有帮助过的人...
(另外:我回答了我自己的问题。这是我应该做的还是我应该编辑我的帖子?会认为人们宁愿看到整个过程而不是让我删除旧的非工作代码......)