所以我的代码如下。我没有收到任何错误,它将节点中的所有内容都放好了。但基于我的调试语句每次插入任何内容时它都会找到根。我不确定这是不对的。但根据作业的输出文件,我的答案是不同的,当涉及树的高度,遍历,我只是平坦我仍然有我的叶计数功能的麻烦。另一个故事。

基于调试语句,看起来一切都正常。但我想我可能需要新鲜的眼睛。我不知道我的遍历是如何改变的,因为它实际上只是我处理应该影响顺序,预订和后序的节点的问题。

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;

只有在第一次调用root之后,任何使用node-&gt; left或node-&gt; right的调用都会使它成为一个中间节点。

要写高度()我会这样做:

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。此外,您正在传递*&amp;节点;它应该是*节点。否则你传递一个指向地址的指针(或参考,我不确定在这种情况下哪个,但两者都不会正确)。您应该将指针传递给Node in,而不是引用。

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归因
不隶属于 StackOverflow
scroll top