0
#include <iostream>
using namespace std;
template <typename T>
// we shouln't use the template here, it will cause a bug
// "argument list for class template "Node" is missingC/C++(441)"
// to fix the bug, check "https://stackoverflow.com/questions/15283195/argument-list-for-class-template-is-missing"
struct Node
{
    T datum;
    Node* left;
    Node* right;
};

// REQUIRES: node represents a valid tree
// MODIFIES: cout 
// EFFECTS: Prints each element in the given tree to stanhdard out
//          with each element followed by a space
void print(const Node *tree)  {
    if(tree) {            // non-empty tree
        cout << tree->datum << " ";
        print(tree->left);
        print(tree->right);
    }
}

I am a beginner in C++, I was trying to learn basic Binary tree print, I don't know how to fix the red line under Node in void print(const Node *tree), I saw some people saying that convert the template T to int would fix the bug, but I don't know why that works.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Yuan01216
  • 13
  • 3
  • Hi! Please post your code as formatted text, not an image: https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question – nathan liang Apr 10 '22 at 02:38
  • 1
    Oh thank you for the instruction and I would follow. – Yuan01216 Apr 10 '22 at 02:46

1 Answers1

0

The print function should also be a template function, the C++ compiler needs you to tell it the specific type of the Node in print function. see below:

#include <iostream>
using namespace std;

template<typename T>
struct Node
{
    T datum;
    Node* left;
    Node* right;
};

template<typename T>
void print(const Node<T>* tree) {
    if (tree == nullptr) {
        return;
    }
    print(tree->left);
    cout << tree->datum << " ";
    print(tree->right);
}
Ramy
  • 72
  • 5