[英]C++ Binary Search Tree Insert via Recursion
所以我的代码如下。 我没有收到任何错误,它可以将所有内容正确放置在节点中。 但是根据我的调试语句,每当插入任何内容时,它都会找到根。 我不确定这是否正确。 但是根据分配的输出文件,当涉及到树的高度,遍历时,我的答案是不同的,而且我的叶子计数功能仍然很麻烦。 另一个故事。
根据调试语句,看起来一切都在正确的地方进行。 但我认为我可能需要新鲜的眼睛。 我完全看不到遍历的变化,因为这实际上仅是我在哪里处理应该影响Inorder,preorder和postorder的节点的问题。
template <class T>
void BT<T>::insert(const T& item)
{
Node<T>* newNode;
newNode = new Node<T>(item);
insert(root, newNode);
}
template <class T>
void BT<T>::insert(struct Node<T> *&root, struct Node<T> *newNode)
{
if (root == NULL)
{
cout << "Root Found" << newNode->data << endl;
root = newNode;
}
else
{
if (newNode->data < root->data)
{
insert(root->left, newNode);
cout << "Inserting Left" << newNode-> data << endl;
}
else
{
insert(root->right, newNode);
cout << "Inserting Right" << newNode->data << endl;
}
}
}
我的高度函数如下,以防万一我的插入物确实好用。
template <class T>
int BT<T>::height() const
{
return height(root);
}
template <class T>
int BT<T>::height(Node<T>* root) const
{
if (root == NULL)
return 0;
else
{
if (height(root->right) > height(root->left))
return 1 + height(root-> right);
return 1 + height(root->left);
}
}
您需要更改调试语句的措辞
确实应该读取(不是“根”节点)
cout << "Leaf Node Found" << newNode->data << endl;
只有在第一次调用它时,它才是根节点,而任何使用node-> left或node-> right的调用都将其作为中间节点。
要编写height(),我会这样做:
template <class T>
int BT<T>::height(Node<T>* root) const
{
if (root == NULL) {return 0;}
return 1 + max(height(root->left),height(root->right));
}
您需要先将root init设置为null。 另外,您正在将*&node传递给; 它应该是* node。 否则,您要传递指向该地址的指针(或引用,在这种情况下我不确定是哪一个,但是两者都不正确)。 您应该传递一个指向Node的指针,而不是引用。
template <class T>
void BT<T>::BT()
{ root = 0;}
template <class T>
void BT<T>::insert(const T& item)
{
Node<T>* newNode;
newNode = new Node<T>(item);
insert(root, newNode);
}
template <class T>
void BT<T>::insert(struct Node<T> *root, struct Node<T> *newNode)
{
/*stuff*/
}
@Vlion:
它应该是一个指向左/右/根指针的指针(即双指针),因此尽管有些不清楚,但发布的代码是正确的。
@Doug:
考虑这样更改插入功能:
template <class T>
void BT<T>::insert(struct Node<T>** root, struct Node<T>* newNode)
{
if (*root == NULL)
{
cout << "Root Found" << newNode->data << endl;
*root = newNode;
}
明确表明您打算更改将作为第一个参数传递的指针(或者更确切地说,将将地址作为第一个参数传递的指针)。这将有助于避免发生诸如刚才发生的那样的混乱。
对此insert()的调用,例如:
insert(&root, newNode);
还将反映您更改指针值的意图。 不过,这只是风格问题,因此如果您不希望更改,我无法争论。
至于检查树是否“正确”,为什么不把它抽出来看看呢? 类似于以下内容:
template class<T>
void printTree(struct Node<T>* node, int level=0)
{
if (!node) {
for (int i=0; i<level; ++i)
cout << " ";
cout << "NULL" << endl;
return;
}
printTree(node->left, level+1);
for (int i=0; i<level; ++i)
cout << " ";
cout << node->data << endl;
printTree(node->right, level+1);
}
(未经测试的代码)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.