0
    #include <bits/stdc++.h>
using namespace std;

struct Node  
{
  int key;
  struct Node *left;
  struct Node *right;
  Node(int k){
      key=k;
      left=right=NULL;
  }
};


int main() {

Node *root=new Node(1);
root->left=new Node(2);
root->right=new Node(3);

cout<<*root<<endl;
}

Why does this code throw an error? I tried to dereference root node by doing *root, but it does not work. What does *root denote?

1 Answers1

0

You must either overload the ostream operator for struct:

std::ostream& operator<<(std::ostream& os, const Node& node)
{
    if (os.good())
    {
        os << node.key << std::endl;
        // print pointer here if needed
        // ...
    }
}

or just write:

cout << root->key << endl;

*root just dereferences the pointer and is of type Node. In C++ you have to specify how to print complex data structures unlike in other languages like python. That's why you cant write cout << *root << endl;.

Thats the same for comparing complex data structures. Therefore you have to overload the ==-operator.

bool operator==(Node *lnode, Node *rnode)
{
    return lnode->key == rnode->key;
}
Bananenkönig
  • 547
  • 4
  • 12
  • Thanks for this. But could you please tell what *root signifies? If I am trying to compare two nodes by : *root != *root1 , It is again throwing an error. Why is it so? –  Apr 29 '21 at 13:20
  • And i edited it again :D Hope this is sufficient for your understanding now :) – Bananenkönig Apr 29 '21 at 13:29