我曾嘗試撰寫代碼來實作二叉搜索樹,但是當我運行我的代碼時沒有輸出任何內容并關閉程式。我認為我的插入函式是正確的,因為我在插入函式的多個位置寫了 cout<<"yes",并顯示了我用于順序遍歷的二叉搜索樹的所有節點,這是在一個簡單的函式中遞回完成的。這是我的代碼:
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *right;
Node *left;
};
void insert(Node **root_ref, int value)
{
Node *temp = new Node();
temp->data = value;
temp->right = NULL;
temp->left = NULL;
Node *current = *root_ref;
if (*root_ref == NULL)
{
*root_ref = temp;
return;
}
while (current != NULL)
{
if ((temp->data < current->data) && (current->left == NULL))
{
current->left = temp;
return;
}
else if ((temp->data > current->data) && (current->right == NULL))
{
current->right = temp;
return;
}
else if ((temp->data > current->data))
{
current = current->right;
}
else
{
current = current->left;
}
}
}
void printinorder(Node *root1)
{
printinorder(root1->left);
cout << " " << root1->data << " ";
printinorder(root1->right);
}
int main()
{
Node *root = NULL;
insert(&root, 60);
insert(&root, 50);
insert(&root, 70);
insert(&root, 30);
insert(&root, 53);
insert(&root, 80);
insert(&root, 65);
printinorder(root);
}
uj5u.com熱心網友回復:
對于初學者,insert當已經存在具有相同值的節點時將值添加到樹時,該函式可能會產生記憶體泄漏,因為在這種情況下,只能評估此 else 陳述句
while (current != NULL)
{
//...
else
{
current = current->left;
}
}
因此,回圈將結束其迭代,盡管已經分配了節點,但不會將任何內容添加到樹中。
該函式可以撰寫為例如以下方式
void insert( Node **root_ref, int value )
{
Node *temp = new Node { value, nullptr, nullptr };
while ( *root_ref != nullptr )
{
if ( ( *root_ref )->data < value )
{
root_ref = &( *root_ref )->right;
}
else
{
root_ref = &( *root_ref )->left;
}
}
*root_ref = temp;
}
在遞回函式中 printinorder
void printinorder(Node *root1)
{
printinorder(root1->left);
cout << " " << root1->data << " ";
printinorder(root1->right);
}
您沒有檢查傳遞的引數是否等于nullptr. 因此該函式呼叫未定義的行為。
函式可以寫成如下方式
std::ostream & printinorder( const Node *root, std::ostream &os = std::cout )
{
if ( root != nullptr )
{
printinorder( root->left, os );
os << " " << root->data << " ";
printinorder( root->right, os );
}
return os;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407987.html
標籤:
上一篇:如何使用sympy求解不等式$5\sin(\theta)-\frac{1}{2}\sin\left(\frac{5\theta}{2}\right)\geq0$?
