Trees and pointers in C?

#include <stdio.h> #include <stdlib.h> struct TreeNode { int key; struct TreeNode* left; struct TreeNode* right; }; struct TreeNode* createNode(int key) { struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); newNode->key = key; newNode->left = newNode->right = NULL; return newNode; } int main() { struct TreeNode* root = createNode(1); root->left = createNode(2); root->right = createNode(3); root->left->left = createNode(4); root->left->right = createNode(5); // Weitere Operationen können hier durchgeführt werden return 0; }

I got this code from ChatGPT. I don't understand the following line:

 struct TreeNode* createNode(int key)

Do I understand correctly that createNode creates a pointer to TreeNode and thus has access to its memory? If so, does it also have access to the memory contents, i.e., what's in it? If so, what exactly does it do for me?

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
2 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
KarlRanseierIII
1 year ago

If you provide the typical graphical representation of a tree, there are edges from the parent node to the child node.

A pointer is a reference type, it contains the memory address of the referenced object.

These references for the successors correspond to the edges of the graphic representation.

In the end, I only need to refer the reference to it in order to access the target, note that

(*node).member /+ ist äquivalent zu */
node->member
regex9
1 year ago

The function createNode attaches a new node that notices a value (key) and returns it (or a pointer to it).

You also have access to the properties of the node (key, left, Right).

How you main-The function can be linked by accessing the properties. First, a root node (root) created. Two further nodes are then applied and connected to it (left, Right).