0

This code snippet is an example I saw online:

struct Node {
    int data;
    Node* Left;
    Node* Right;
}

Node* CreateNode(int data) {
    Node* newNode = new Node();
    newNode->data = data;
    newNode->Left = newNode->Right = nullptr;
    return newNode;
}

I cannot understand, why are the nodes inside using pointers, instead of just simply the nodes themselves?

And also, why is the function for creating nodes returning a pointer?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    If a node contains another node, this will result in an infinite amount of nodes. Does your computer have an infinite amount of RAM? – Sam Varshavchik Aug 18 '22 at 22:08
  • Pointers can be _null_ which allows the tree to have some kind of end. You can not insist that every node contains another node, because the universe would not have enough memory to create one node. – Drew Dormann Aug 18 '22 at 22:10
  • What is the size of `struct node { int data; node child; }`? to calculate the size of the node you need to know the size of the node. So there is no way for the compiler to create such a thing. – Jerry Jeremiah Aug 18 '22 at 22:11
  • Also, the creation function is _not_ a pointer. It _returns_ a `Node*`, if that is what is making you think the function is a pointer. – Drew Dormann Aug 18 '22 at 22:12
  • 4
    As you're using C++ rather than C, why have `CreateNode` vs just giving the struct a constructor? – Chris Aug 18 '22 at 22:13
  • The purpose of a tree is not just to have nodes, but to store data. Where would you put the data? – Tim Roberts Aug 18 '22 at 22:54
  • How would you link the nodes together, in the proper order, without some kind of pointer? – Thomas Matthews Aug 19 '22 at 00:19
  • Additional syntax note: you need a semicolon after the struct. `struct Node { ... };` – Chris Aug 19 '22 at 05:52

0 Answers0