I found this code somewhere that is a simple implementation of a tree. Is there a reason why the left
and right
have to be pointers to Node
? In other words, can you still implement a tree without left
and right
being pointers and just being of type Node
? If so, could someone please provide an example
#include <iostream>
struct Node {
int data;
struct Node* left;
struct Node* right;
Node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
int main(int argc, char* argv[]) {
struct Node* root = new Node(0);
root->left = new Node(1);
root->right = new Node(0);
root->right->left = new Node(1);
root->right->right = new Node(0);
root->right->left->left = new Node(1);
root->right->left->right = new Node(1);
std::cout << root->data << "\n";
}
All help is appreciated, thanks!
A simpler example of a linked list, ie each Node
has only one next
:
struct Node {
Node next;
};
C++ does not allow this, you will get an error, but lets consider for a moment there was no error. Then every Node
contains another Node
and that member again contains another Node
. And that Node
has another member next
which is a Node
too. This Node
has a member next
of type Node
. That Node
has another member next
which is a Node
too. This Node
has a member next
of type Node
... ad infinitum.
Maybe you are coming from a language where objects are actually references. In C++ an object is the object. It cannot be "no object". Objects cannot be NULL
.
Pointers on the other hand can point to an object, but they can also point nowhere. This is fine:
struct Node {
Node* next;
};
Each Node
has a member next
that either points to a Node
or not.
One way to see why the first is not allowed in C++ is that sizes of members must be known to the compiler. The size of a pointer is the same no matter what is the size of the object itself. However, as explained above, it is not a restriction of C++, but rather it is impossible to have something that contains itself infinite many times.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.