這是學校處理遞歸和二叉樹實驗的一部分。如果我去插入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;
}
但我相信麻煩的是搜索功能中,特別通過引用父節點指針:
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;
}
我有輸出樹的功能,並有檢查了一棵樹我手動建成並正常工作:
void inorder(Node *t)
{
if (t!=NULL) {
if (t->leftchild!=NULL)
inorder(t->leftchild);
cout << t->data << ", ";
if (t->rightchild!=NULL)
inorder(t->rightchild);
}
}
不找只是尋找一個區域,我應該看一個答案。
您應該編輯原始問題以使問題更清楚,但答案應該是獲得校驗標記的答案。如果你要回答你自己的問題,不僅要考慮「這裏是工作代碼」,而且就像你是一個試圖從閱讀討論中學習的人。由於你是新人,我已經做了一些編輯,以幫助提供一些想法與你的原創:http://stackoverflow.com/revisions/8306096/1 – HostileFork
我更新了你的答案,以顯示我在說什麼。請注意,如果你打算分享你的'inorder'打印功能,那麼你可能會提出這個問題,因爲它不是在回答過程中學到的「新東西」......所以我把它移到了題。您可以看到,在將短代碼示例與描述性文本交織在一起而不是粘貼長滾動的代碼框時,將會更加輕鬆。另外StackOverflow就像維基百科一樣,將修訂版的歷史記錄保存到問答環節中,所以事情不會丟失:http://stackoverflow.com/revisions/8317919/1 – HostileFork